C# DateTime

DateTime

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.

Tip:DateTime is a useful struct.
It offers many useful methods and properties.
It helps with date and time computations.

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. The arguments to the constructor must match a real date that occurred.

New keyword, constructor invocation

Next:This example also shows how to write a DateTime to the console. It also compares a DateTime against the Today value.

Console.WriteLine
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

Yesterday

Here we 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
Note

The example displays 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.

Note:The example was run on November 30, 2008. The output will naturally vary depending on the day you run it.

And:DateTime.Today is always set to the machine's local time, which depends on the current system.

Tomorrow

Plus

Here we 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. We use the AddDays method.

This method is static method because it does 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 go back in time.

Static Method

Note:The XML comments here again will be useful if you need to use this method in many places.

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

First day

First

Next, we introduce first day method. 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 pass it the year as an int.

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

Programming tip

Here we find the last day in any year. 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 programmatically find it.

Tip:This method is ideal for when you want to count days, as for a database range query for a certain year.

Program that finds last day: 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 one 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
Method call

In this example, we see two overloaded methods. These can make the calling conventions more natural and easier to remember. Recall that overloaded methods are inferred at compile-time, not runtime.

Overload

Tip:It is better to use the DateTime constructor, rather than DateTime.Parse. This has better performance and syntax.

Elapsed

Next, we 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. We further cover TimeSpan in a separate article.

DateTime, ElapsedDateTime SubtractTimeSpan

Methods

Squares

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

Method signatures. Many of these methods receive a double type, which is a numeric type used similarly to int. Double values can store decimal places. We provide detailed information on doubles and numeric casts.

DoubleNumeric Casts

Add:This requires a TimeSpan to be received. You will need to use the TimeSpan constructor first. The Subtract method is also available.

AddDays:Receives a double integer, which adds or subtracts days. We can use AddHours, AddMinutes, AddSeconds and more.

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

FromBinary, ToBinary:Parses or creates a binary date. You may have a binary date if you have serialized a date to a file.

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

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

ToLocalTime:Normally your dates will be in the local time. You can convert an external DateTime it to the local time zone with this.

FromOADate

Convert or change

Dates are stored in many formats. Programs such as Excel store dates in a special double format. In the C# language we can use FromOADate to read in these dates. And we can output this format with ToOADate.

Tip:FromOADate and ToOADate are useful for converting Excel dates to C# dates. May also be useful for Visual FoxPro or Microsoft Access.

Also:I have used this for Microsoft.Office.Excel.Interop. Detailed examples of Excel interop are available.

FromOADateExcel

Parse

String type

It is possible to parse DateTime instances. This converts a string value into a DateTime. The Try methods avoid expensive exceptions that would otherwise be thrown. If you have lots of invalid data, use TryParse.

DateTime.ParseTryParse

ToString

String

A DateTime can be converted into a string. This is useful for display or for writing to a file. With ToString, and the variants of ToString, we easily format a DateTime struct as text.

Note:These methods include ToString, ToLongDateString, ToLongTimeString, ToShortDateString and ToShortTimeString.

Tip:It is necessary to experiment to find the best one. This is usually the most compatible one.

DateTime Format

DayOfWeek

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

DayOfWeek

Properties

Property

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.

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

Day, Month, Year:These return a component of the time. Note that this is not the interval since any other date.

Now, UtcNow:These return the current DateTime, with all of the fields correctly filled. DateTime.Now is a useful property.

DateTime.Now

Today:Gets the current date in the form of a DateTime instance. Today does not contain any information about the time.

DateTime.Today

Null

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.

Note:Please find more information on DateTime structs and the null value here.

DateTime.MinValue: NullNull Tips

Summary

We saw useful methods for finding relative dates DateTime structures in the C# language. There is helpful material on MSDN. This isn't intended to be the only resource you consult, but a complementary one.


C#: Time