C# DateTime Examples

by Sam Allen - Updated January 18, 2010

You want to use the DateTime type in the C# programming language, and also need various methods to find important days, such as yesterday, tomorrow, the first of the year, and the last day. The DateTime type in the C# language provides useful methods and properties for computing these values. This document has several useful methods and shows their output, using the C# programming language.

Use DateTime to compute relative dates.               
... Create new DateTimes with overloaded constructors.
... Review other DateTime properties.                 

Constructor

For the DateTime type in the C# programming 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, and also to how you can compare 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 of the program ---
    The second line depends on the local date on your computer.

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

Finding yesterday

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

=== Example 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 of the program ===

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 very useful here because you may want to put these methods in a helper class, which 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.

(See DateTime Subtract Method.)

Finding 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.

=== Example 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 of the program ===

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.

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.

Finding the first day in year

Here we see how you can use a simple helper method to find the first day in a year. This is easy to do because the first day is always "1-1-____".

=== Example 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 of the program ===

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

Description. We use an overloaded method here, which can make usage of the methods easier as 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.

Finding the 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.

=== Example 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 of the program ===

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 much better to use the new DateTime constructor, rather than DateTime.Parse to create new DateTimes. This is both for performance and for simplicity of syntax.

Find time 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.

(See Days Elapsed From DateTime.)

DateTime methods

In this section, we look at methods on the DateTime type specifically. Here are the author's notes on the DateTime methods that are useful. This is not exhaustive, but complementary to MSDN.

(Visit msdn.microsoft.com.)

(See FromOADate and Excel Dates.)

(See DateTime.Parse String Method.)

(See DateTime.ParseExact Usage.)

(See DateTime Format Examples.)

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 very 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, but 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, as 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.

Description of 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.

(See Numeric Casts and Numbers.)

DateTime properties

In this section, we look at properties on the DateTime type. These properties, also listed at the link to MSDN above, are useful abstractions for getting specific aspects of your DateTime. This table contains my notes and a few hints.

(See DateTime.Now for Getting Current Time.)

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.Today
This returns "a DateTime set to today's date, with the time component set to
00:00:00." From DateTime.Today 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. The author recommends checking MSDN for all the specifics,
as they are not useful for me to repeat here.

Null DateTime structs

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

(See DateTime Null, Using DateTime.MinValue Default.)

Summary

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

(Do not copy this page.)

Dot Net Perls | Search
DateTime | DateTime Format Examples | DateTime Null, Using DateTime.MinValue Default | DateTime.Now for Getting Current Time | DateTime.Parse String Method | DateTime.ParseExact Usage
C# | SaveFileDialog Tutorial | IntegralHeight Property (Windows Forms) | Array.FindIndex Method | File.Replace Method
© 2010 Sam Allen. All rights reserved.
Dot Net Perls | Sam Allen