C# DateTime

DateTime type illustration

Time representations are complicated. The C# language provides the DateTime type as evidence. This type can be used to get the current time and relative times such as yesterday, tomorrow and certain days in years. DateTime offers many useful methods and properties for these computations.

This C# tutorial uses DateTime. It computes relative dates and uses DateTime constructors and properties.

Constructor

For the DateTime type in the C# language and .NET Framework, you can use the instance constructor with the 'new' operator to instantiate a new DateTime instance. Please note that the arguments to the constructor must match to a real date that occurred. This example also shows how you can write a DateTime to the console. It also compares a DateTime against the Today value.

Program that uses DateTime constructor [C#]

using System;

class Program
{
    static void Main()
    {
	// This DateTime is constructed with an instance constructor.
	// ... We write it to the console.
	// ... If this is today, the second line will be "True".
	DateTime value = new DateTime(2010, 1, 18);
	Console.WriteLine(value);
	Console.WriteLine(value == DateTime.Today);
    }
}

Output
    The second line depends on the local date on your computer.

1/18/2010 12:00:00 AM
True

Find yesterday

Here we see how to subtract one day from the current day. We do this by adding -1 to the current day. This is necessary because no "Subtract Days" method is provided. An extension method could help depending on your style.

Program that uses DateTime [C#]

using System;

class Program
{
    static void Main()
    {
	Console.WriteLine("Today: {0}", DateTime.Today);

	DateTime y = GetYesterday();
	Console.WriteLine("Yesterday: {0}", y);
    }

    /// <summary>
    /// Gets the previous day to the current day.
    /// </summary>
    static DateTime GetYesterday()
    {
	// Add -1 to now
	return DateTime.Today.AddDays(-1);
    }
}

Output

Today: 11/30/2008 12:00:00 AM
Yesterday: 11/29/2008 12:00:00 AM

Description. What the example displays is the current day. Note that the Console.WriteLine implicitly converts the DateTime.Today argument using its ToString method. XML comments are useful here because you may want to put these methods in a helper class. This would make them reusable across projects.

The example was run on November 30, 2008. The output will naturally vary depending on the day you run it. DateTime.Today is always set to the machine's local time.

DateTime Subtract Method

Find tomorrow

Here we see how you can add one using the DateTime Add method to figure out tomorrow. This is useful for using date queries in databases, as you usually have to select a range of dates.

Program that uses AddDays [C#]

using System;

class Program
{
    static void Main()
    {
	Console.WriteLine("Today: {0}", DateTime.Today);

	DateTime d = GetTomorrow();
	Console.WriteLine("Tomorrow: {0}", d);
    }

    /// <summary>
    /// Gets the next day, tomorrow.
    /// </summary>
    static DateTime GetTomorrow()
    {
	return DateTime.Today.AddDays(1);
    }
}

Output

Today: 11/30/2008 12:00:00 AM
Tomorrow: 12/1/2008 12:00:00 AM

Description. This method and the previous ones are static methods because they do not require state to be saved. DateTime.Today is not an instance of the class. DateTime.Add uses offsets, meaning it accepts both negative and positive numbers. Here we literally go back in time.

Extensible markup language (XML)

Using XML comments. The XML comments here again will be useful if you need to use this method in many places. XML comments are not always useful for private methods.

First day in year

1

You can use a simple helper method to find the first day in a year. We use an overloaded method. This can make usage of the methods easier—there are fewer method names. If you want the current year, don't call the above method with a parameter. The DateTime parameter of the second DateTime method above can be any time in the required year. It could be a better design to simply pass it the year as an int.

Program that uses new DateTime [C#]

using System;

class Program
{
    static void Main()
    {
	Console.WriteLine("First day: {0}",
	    FirstDayOfYear());

	DateTime d = new DateTime(1999, 6, 1);
	Console.WriteLine("First day of 1999: {0}",
	    FirstDayOfYear(d));
    }

    /// <summary>
    /// Gets the first day of the current year.
    /// </summary>
    static DateTime FirstDayOfYear()
    {
	return FirstDayOfYear(DateTime.Today);
    }

    /// <summary>
    /// Finds the first day of year of the specified day.
    /// </summary>
    static DateTime FirstDayOfYear(DateTime y)
    {
	return new DateTime(y.Year, 1, 1);
    }
}

Output

First day: 1/1/2008 12:00:00 AM
First day of 1999: 1/1/1999 12:00:00 AM

Last day in year

Here we see how to find the last day in any year. Note that leap years make this more complicated, as February may have 28 or 29 days. Because of leap year, you cannot use the length of the year as a constant. We can find it programmatically using the new DateTime constructor. This method is ideal for when you want to count days, as for a database range query for a certain year.

Program that uses new DateTime [C#]

using System;

class Program
{
    static void Main()
    {
	Console.WriteLine("Last day: {0}",
	    LastDayOfYear());

	DateTime d = new DateTime(1999, 6, 1);
	Console.WriteLine("Last day of 1999: {0}",
	    LastDayOfYear(d));
    }

    /// <summary>
    /// Finds the last day of the year for today.
    /// </summary>
    static DateTime LastDayOfYear()
    {
	return LastDayOfYear(DateTime.Today);
    }

    /// <summary>
    /// Finds the last day of the year for the selected day's year.
    /// </summary>
    static DateTime LastDayOfYear(DateTime d)
    {
	// 1
	// Get first of next year
	DateTime n = new DateTime(d.Year + 1, 1, 1);
	// 2
	// Subtract 1 from it
	return n.AddDays(-1);
    }
}

Output

Last day: 12/31/2008 12:00:00 AM
Last day of 1999: 12/31/1999 12:00:00 AM

Description. We see two overloaded methods here, which can make the calling conventions more natural and easier to remember. Recall that overloaded methods are inferred at compile time, not runtime. It is better to use the new DateTime constructor, rather than DateTime.Parse to create new DateTimes. This is both for performance and simplicity of syntax.

Elapsed since date

Here we mention that you can find the "age" of a certain date, and how long ago it was in time. You can do this with DateTime.Subtract, which will return a TimeSpan.

Days Elapsed From DateTime

DateTime methods

Method call

Continuing on, let's look at methods on the DateTime type specifically. Here are my notes on the DateTime methods that are useful. This is not exhaustive, but complementary to MSDN.

FromOADate and Excel Dates DateTime.Parse String Method DateTime.ParseExact Usage DateTime Format

DateTime.Add This requires a TimeSpan to be received. You will need to use the TimeSpan constructor first.

DateTime.AddDays Receives a positive or negative double integer, which adds or subtracts days. We see examples in this document.

DateTime.AddHours DateTime.AddMilliseconds DateTime.AddMinutes DateTime.AddMonths DateTime.AddSeconds DateTime.AddYears These are self-explanatory and receive a positive or negative double, for adding or subtracting the specified part of the DateTime.

DateTime.AddTicks One tick is considered one millisecond. This method might be useful when used with Environment.AddTicks.

DateTime.Compare DateTime.CompareTo These tell you whether one date is bigger or smaller than another. Mainly used for sorting. However, you don't need to implement a custom sort for DateTime normally.

DateTime.DaysInMonth Helper method that will tell you how many days are in a month. I haven't used it but it is useful to know about.

DateTime.Equals This is the sample as op_Equality, the == operator.

DateTime.FromBinary DateTime.ToBinary Parses or creates a binary date. You may have a binary date if you have serialized a date to a file. I haven't used these.

DateTime.FromFileTime DateTime.FromFileTimeUtc DateTime.ToFileTime DateTime.ToFileTimeUtc Use these for when you have file times you need to convert. I haven't used this.

DateTime.FromOADate DateTime.ToOADate Useful for converting Excel dates to C# dates. May also be useful for Visual FoxPro or Microsoft Access. I have used this for Microsoft.Office.Excel.Interop.

DateTime.GetDateTimeFormats This provides functionality related to formatting. It is overloaded and may be helpful rarely.

DateTime.GetDaylightSavingTime Daylight saving time is what we get for letting our politicians pretend to be scientists. Not useful in Arizona.

DateTime.IsLeapYear Leap years have 29 days in February. Leap year is here to make programmers' lives hard and has little other impact.

DateTime.Subtract Takes away one DateTime or TimeSpan from the first one. This isn't as useful as the Add methods, as you must provide a more complex parameter.

DateTime.ToLocalTime Normally your dates will be in the local time. If you acquire an external DateTime, you can convert it to the local timezone with this.

DateTime.Parse DateTime.ParseExact DateTime.TryParse DateTime.TryParseExact You will need to consult MSDN for information on exactly what formats can be parsed. If you have lots of invalid data, use TryParse. It will capture its exceptions and improve performance.

DateTime.ToString DateTime.ToLongDateString DateTime.ToLongTimeString DateTime.ToShortDateString DateTime.ToLongTimeString For these ToString methods, it is best to simply experiment to find the one you like best or that is most compatible. I also recommend checking MSDN's articles on DateTime format strings.

Method signatures. Many of the methods above receive a double type, which is a numeric type used similarly to int. Double values can store decimal places.

Numeric Casts

DayOfWeek property

You can find more detailed information on the DayOfWeek property on the DateTime instance. This allows you to determine if a date is a Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, or Sunday. Please see the specific article.

DayOfWeek Enum

Today property

You can use the Today property for getting the current date in the form of a DateTime instance. Today does not contain any information about the time.

DateTime.Today

Now property

The current time (now)

The Now property contains information about the current date as well as the current time. It is a more exact version of the Today property, with time information as well.

DateTime.Now Gets Current Time

More properties

Property (Icon copyright Microsoft)

Let's look at properties on the DateTime type. These properties, also listed at MSDN, are useful abstractions. They return specific aspects of your DateTime. This table contains my notes and a few hints.

DateTime.Date This returns only the date component of the DateTime. It has the "time value set to 12:00:00 midnight (00:00:00)." From DateTime.Date Property (System) at MSDN.

DateTime.Day DateTime.DayOfWeek DateTime.DayOfYear DateTime.Hour DateTime.Millisecond DateTime.Minute DateTime.Month DateTime.Second DateTime.Ticks DateTime.TimeOfDay DateTime.Year These return a component of the time. Note that this is not the interval since any other date. They just return the single part of the date. For example, Day returns "the day component, expressed as a value between 1 and 31." From DateTime.Day Property (System) at MSDN.

DateTime.Now DateTime.UtcNow These return the current DateTime, with all of the fields correctly filled in. DateTime.Now is one of the most common properties to use.

DateTime.Kind Returns a DateTimeKind. I recommend checking MSDN for all the specifics—they are not useful for me to repeat here.

Null DateTime structs

Null keyword

The DateTime struct in the C# programming language is a value type and not a reference type. For this reason you cannot use a null DateTime. You can either use a nullable DateTime class or DateTime.MinValue to indicate an empty DateTime. Please find more information on DateTime structs and the null value here.

DateTime.MinValue: Null Null Tips

Summary

The C# programming language

In this set of examples, we saw several useful methods for finding relative dates DateTime structures in the C# programming language. We reviewed some of the literature on MSDN. This isn't intended to be the only resource you consult, but a complementary one.

Time Representations
.NET