C# Date Time Tutorial

1- The related classes date and time in C#

In .NET Framework, System.DateTime is a class represents dates and times. The value of DateTime is between 12:00:00 midnight, January 1, 0001 to 11:59:59 P.M., December 31, 9999 A.D.
There are many constructors to create DateTime object:
DateTime Constructors
public DateTime(int year, int month, int day)

public DateTime(int year, int month, int day, Calendar calendar)

public DateTime(int year, int month, int day, int hour, int minute, int second)

public DateTime(int year, int month, int day, int hour, int minute, int second, Calendar calendar)

public DateTime(int year, int month, int day, int hour, int minute, int second, DateTimeKind kind)

public DateTime(int year, int month, int day, int hour, int minute, int second, int millisecond)

public DateTime(int year, int month, int day, int hour,
                    int minute, int second, int millisecond, Calendar calendar)

public DateTime(int year, int month, int day, int hour,
                   int minute, int second, int millisecond, Calendar calendar, DateTimeKind kind)

public DateTime(int year, int month, int day, int hour,
                    int minute, int second, int millisecond, DateTimeKind kind)

public DateTime(long ticks)

public DateTime(long ticks, DateTimeKind kind)
  • TODO - EXAMPLE
Now is a static attribute of DateTime, it returns DateTime object describe the current date time.
// The current datetime:

DateTime now = DateTime.Now;

Console.WriteLine("Now is "+ now);

2- DateTime Attributes

DateTimePropertiesExample.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DateTimeTutorial
{
    class DateTimePropertiesExample
    {

        public static void Main(string[] args)
        {
            // Create a DateTime (year, month, day, hour, minute, second).
            DateTime aDateTime = new DateTime(2005, 11, 20, 12, 1, 10);

            // Print out infos:

            Console.WriteLine("Day:{0}", aDateTime.Day);
            Console.WriteLine("Month:{0}", aDateTime.Month);
            Console.WriteLine("Year:{0}", aDateTime.Year);
            Console.WriteLine("Hour:{0}", aDateTime.Hour);
            Console.WriteLine("Minute:{0}", aDateTime.Minute);
            Console.WriteLine("Second:{0}", aDateTime.Second);
            Console.WriteLine("Millisecond:{0}", aDateTime.Millisecond);

            // Enum {Monday, Tuesday,... Sunday}
            DayOfWeek dayOfWeek = aDateTime.DayOfWeek;   


            Console.WriteLine("Day of Week:{0}", dayOfWeek );
           

            Console.WriteLine("Day of Year: {0}", aDateTime.DayOfYear);

            // An object described only time (hour minute, ..)
            TimeSpan timeOfDay = aDateTime.TimeOfDay;

            Console.WriteLine("Time of Day:{0}", timeOfDay);

            // Convert to Ticks (1 second= 10.000.000 Ticks)
            Console.WriteLine("Tick:{0}", aDateTime.Ticks);

            // {Local, Itc, Unspecified}
            DateTimeKind kind = aDateTime.Kind;

            Console.WriteLine("Kind:{0}", kind);

            Console.Read();
        }
    }

}
Running the example:

3- Adding and Subtracting DateTime

Datetime provide methods which allow you to add, or subtract one period of time . Timespan is a class that contains information of a period of time, it may participate as a parameter in the method of adding or subtracting time of  DateTime.
Example:
AddSubtractExample.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DateTimeTutorial
{
   class AddSubtractExample
   {

       public static void Main(string[] args)
       {
           // Thời điểm hiện tại.
           DateTime aDateTime = DateTime.Now;

           Console.WriteLine("Now is " + aDateTime);

           // Một khoảng thời gian.
           // 1 giờ + 1 phút
           TimeSpan aInterval = new System.TimeSpan(0, 1, 1, 0);

           // Thêm khoảng thời gian.
           DateTime newTime = aDateTime.Add(aInterval);


           Console.WriteLine("After add 1 hour, 1 minute: " + newTime);


           // Trừ khoảng thời gian.
           newTime = aDateTime.Subtract(aInterval);

           Console.WriteLine("After subtract 1 hour, 1 minute: " + newTime);

           Console.Read();
       }
   }

}
Running the example:
 DateTime ​class also have methods which  allows to add  units of time, such as:
  • AddYears
  • AddDays
  • AddMinutes
  • ...
Example:
AddSubtractExample2.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DateTimeTutorial
{
    class AddSubtractExample2
    {
        public static void Main(string[] args)
        {
            // The current time.
            DateTime aDateTime = DateTime.Now;

            Console.WriteLine("Now is " + aDateTime);           

            // Add one year.
            DateTime newTime = aDateTime.AddYears(1);


            Console.WriteLine("After add 1 year: " + newTime);

            // Subtract 1 hour
            newTime = aDateTime.AddHours(-1);

            Console.WriteLine("After add -1 hour: " + newTime);

            Console.Read();
        }
    }

}
Running the example:
Sometimes you need to find the first day or last day of a particular month or year. For example, you questioned that how many days does February 2015 have? 28 or 29. For example, below are a few utility methods to do this:
FirstLastDayDemo.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DateTimeTutorial
{
    class FirstLastDayDemo
    {
        public static void Main(string[] args)
        {

            Console.WriteLine("Today is " + DateTime.Today);

            DateTime yesterday = GetYesterday();

            Console.WriteLine("Yesterday is " + yesterday);

            // The first day of February 2015
            DateTime aDateTime = GetFistDayInMonth(2015, 2);

            Console.WriteLine("First day of 2-2015: " + aDateTime);

            // The last day of February 2015
            aDateTime = GetLastDayInMonth(2015, 2);

            Console.WriteLine("Last day of 2-2015: " + aDateTime);

            // The first day of 2015
            aDateTime = GetFirstDayInYear(2015);

            Console.WriteLine("First day year 2015: " + aDateTime);

            // The last day of 2015
            aDateTime = GetLastDayInYear(2015);

            Console.WriteLine("First day year 2015: " + aDateTime);

            Console.Read();
        }

        // Returns Yesterday.
        public static DateTime GetYesterday()
        {
            // Today.
            DateTime today = DateTime.Today;

            // Returns Yesterday.
            return today.AddDays(-1);
        }

        // Returns the first day of the year
        public static DateTime GetFirstDayInYear(int year)
        {
            DateTime aDateTime = new DateTime(year, 1, 1);
            return aDateTime;
        }

        // Returns the last day of the year
        public static DateTime GetLastDayInYear(int year)
        {
            DateTime aDateTime = new DateTime(year +1, 1, 1);

            // Subtract 1 day.
            DateTime retDateTime = aDateTime.AddDays(-1);

            return retDateTime;
        }

        // Return first day of Month.
        public static DateTime GetFistDayInMonth(int year, int month)
        {
            DateTime aDateTime = new DateTime(year, month, 1);

            return aDateTime;
        }

        // Return last day of Month.
        public static DateTime GetLastDayInMonth(int year, int month)
        {
            DateTime aDateTime = new DateTime(year, month, 1);

            // Add 1 month and substract 1 day.
            DateTime retDateTime = aDateTime.AddMonths(1).AddDays(-1);

            return retDateTime;
        }

    }

}
Running the example:

4- Time interval

You have two DateTime objects, you can calculate the interval between two subjects, the results is TimeSpan object.
IntervalDemo.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DateTimeTutorial
{
    class IntervalDemo
    {
        public static void Main(string[] args)
        {
            // The current time.
            DateTime aDateTime = DateTime.Now;

            // Time in 2000
            DateTime y2K = new DateTime(2000,1,1);

            // Interval from 2000 until now
            TimeSpan interval = aDateTime.Subtract(y2K);


            Console.WriteLine("Interval from Y2K to Now: " + interval);

            Console.WriteLine("Days: " + interval.Days);
            Console.WriteLine("Hours: " + interval.Hours);
            Console.WriteLine("Minutes: " + interval.Minutes);
            Console.WriteLine("Seconds: " + interval.Seconds);
 

            Console.Read();
        }
    }

}
Running the example:

5- Compare two DateTime

DateTime has a static method is  Compare. Method used to compare which subject is earlier in 2   DateTime objects.
// If return value < 0 means firstDateTime is earlier
// If return value > 0 means firstDateTime is laster
// If return value = 0 means firstDateTime and secondDateTime same time

public static int Compare(DateTime firstDateTime, DateTime secondDateTime);
CompareDateTimeExample.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DateTimeTutorial
{
    class CompareDateTimeExample
    {
        public static void Main(string[] args)
        {
            // Current time.
            DateTime firstDateTime = new DateTime(2000, 9, 2);

            DateTime secondDateTime = new DateTime(2011, 1, 20);

            int compare = DateTime.Compare(firstDateTime, secondDateTime);

            Console.WriteLine("First DateTime: " + firstDateTime);
            Console.WriteLine("Second DateTime: " + secondDateTime);

            Console.WriteLine("Compare value: " + compare);// -1

            if (compare < 0)
            {
                // firstDateTime is earlier than secondDateTime
                Console.WriteLine("firstDateTime is earlier than secondDateTime");
            }
            else
            {
                // firstDateTime is laster than secondDateTime
                Console.WriteLine("firstDateTime is laster than secondDateTime");
            }

            Console.Read();
        }
    }

}
Running the example:

6- Formatting DateTime

Formating  Datetime  means that converting DateTime object to a string according to a certain pattern, for example in the day/month/year  format  ... or specific locale format.
GetDateTimeFormats method of DateTime:
  • Converts the value of this instance to all the string representations supported by the standard date and time format specifiers.
AllStandardFormatsDemo.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DateTimeTutorial
{
    class AllStandardFormatsDemo
    {
        public static void Main(string[] args)
        {

            DateTime aDateTime = new DateTime(2015, 12, 20, 11, 30, 50);

            // An array of string results supported formats.
            string[] formattedStrings = aDateTime.GetDateTimeFormats();

            foreach (string format in formattedStrings)
            {
                Console.WriteLine(format);
            }


            Console.Read();
        }
    }

}
Running the example:
Example above has listed  the strings after formatting a DateTime object according to available standards supported by .NET. To obtain format according to a sample, you  use one of the following methods:
 
Methods Description
ToString(String, IFormatProvider) Converts the value of the current DateTime object to its equivalent string representation using the specified format (String param) and culture-specific format information (IFormatProvider param).
ToString(IFormatProvider)

Converts the value of the current DateTime object to its equivalent string representation using the specified culture-specific format information.

ToString(String)

Converts the value of the current DateTime object to its equivalent string representation using the specified format and the formatting conventions of the current culture.

The example below  formats datetime in the 'd'  format, and specify the culture in parameter.
SimpleDateTimeFormat.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Globalization;

namespace DateTimeTutorial
{
    class SimpleDateTimeFormat
    {
        public static void Main(string[] args)
        {

            DateTime aDateTime = new DateTime(2015, 12, 20, 11, 30, 50);

            Console.WriteLine("DateTime: " + aDateTime);

            String d_formatString = aDateTime.ToString("d");

            Console.WriteLine("Format 'd' : " + d_formatString);

            // en-US Culture
            CultureInfo enUs = new CultureInfo("en-US");

            // ==> 12/20/2015 (MM/dd/yyyy)
            Console.WriteLine("Format 'd' & en-US: " + aDateTime.ToString("d", enUs));

            // vietnam Culture.
            CultureInfo viVn = new CultureInfo("vi-VN");

            // ==> 12/20/2015 (dd/MM/yyyy)
            Console.WriteLine("Format 'd' & vi-VN: " + aDateTime.ToString("d", viVn));


            Console.Read();
        }
    }

}
Running the example:
The standard characters format:
Code Pattern
"d" Sort date
"D" Long date
"f" Full date time. Short time.
"F" Full date time. Long time.
"g" General date time. Short time.
"G" General date time. Long time.
"M", 'm" Month/day.
"O", "o" Round-trip date/time.
"R", "r" RFC1123
"s" Sortable date time.
"t" Sort time.
"T" Long time.
"u" Universal sortable date time.
"U" Universal full date time.
"Y", "y" Year month.
SimpleDateTimeFormatAll.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DateTimeTutorial
{
    class SimpleDateTimeFormatAll
    {
        public static void Main(string[] args)
        {
            char[] formats = {'d', 'D','f','F','g','G','M', 'm','O', 'o','R', 'r','s','t','T','u','U','Y', 'y'};


            DateTime aDateTime = new DateTime(2015, 12, 20, 11, 30, 50);

            foreach (char ch in formats)
            {
                Console.WriteLine("\n======" + ch + " ========\n");

                // An array of string results supported formats.
                string[] formattedStrings = aDateTime.GetDateTimeFormats(ch);

                foreach (string format in formattedStrings)
                {
                    Console.WriteLine(format);
                }
            }
          


            Console.ReadLine();
        }
    }

}
Running the example

======d ========

12/20/2015
12/20/15
12/20/15
12/20/2015
15/12/20
2015-12-20
20-Dec-15

======D ========

Sunday, December 20, 2015
December 20, 2015
Sunday, 20 December, 2015
20 December, 2015

======f ========

Sunday, December 20, 2015 11:30 AM
Sunday, December 20, 2015 11:30 AM
Sunday, December 20, 2015 11:30
Sunday, December 20, 2015 11:30
December 20, 2015 11:30 AM
December 20, 2015 11:30 AM
December 20, 2015 11:30
December 20, 2015 11:30
Sunday, 20 December, 2015 11:30 AM
Sunday, 20 December, 2015 11:30 AM
Sunday, 20 December, 2015 11:30
Sunday, 20 December, 2015 11:30
20 December, 2015 11:30 AM
20 December, 2015 11:30 AM
20 December, 2015 11:30
20 December, 2015 11:30

======F ========

Sunday, December 20, 2015 11:30:50 AM
Sunday, December 20, 2015 11:30:50 AM
Sunday, December 20, 2015 11:30:50
Sunday, December 20, 2015 11:30:50
December 20, 2015 11:30:50 AM
December 20, 2015 11:30:50 AM
December 20, 2015 11:30:50
December 20, 2015 11:30:50
Sunday, 20 December, 2015 11:30:50 AM
Sunday, 20 December, 2015 11:30:50 AM
Sunday, 20 December, 2015 11:30:50
Sunday, 20 December, 2015 11:30:50
20 December, 2015 11:30:50 AM
20 December, 2015 11:30:50 AM
20 December, 2015 11:30:50
20 December, 2015 11:30:50

======g ========

12/20/2015 11:30 AM
12/20/2015 11:30 AM
12/20/2015 11:30
12/20/2015 11:30
12/20/15 11:30 AM
12/20/15 11:30 AM
12/20/15 11:30
12/20/15 11:30
12/20/15 11:30 AM
12/20/15 11:30 AM
12/20/15 11:30
12/20/15 11:30
12/20/2015 11:30 AM
12/20/2015 11:30 AM
12/20/2015 11:30
12/20/2015 11:30
15/12/20 11:30 AM
15/12/20 11:30 AM
15/12/20 11:30
15/12/20 11:30
2015-12-20 11:30 AM
2015-12-20 11:30 AM
2015-12-20 11:30
2015-12-20 11:30
20-Dec-15 11:30 AM
20-Dec-15 11:30 AM
20-Dec-15 11:30
20-Dec-15 11:30

======G ========

12/20/2015 11:30:50 AM
12/20/2015 11:30:50 AM
12/20/2015 11:30:50
12/20/2015 11:30:50
12/20/15 11:30:50 AM
12/20/15 11:30:50 AM
12/20/15 11:30:50
12/20/15 11:30:50
12/20/15 11:30:50 AM
12/20/15 11:30:50 AM
12/20/15 11:30:50
12/20/15 11:30:50
12/20/2015 11:30:50 AM
12/20/2015 11:30:50 AM
12/20/2015 11:30:50
12/20/2015 11:30:50
15/12/20 11:30:50 AM
15/12/20 11:30:50 AM
15/12/20 11:30:50
15/12/20 11:30:50
2015-12-20 11:30:50 AM
2015-12-20 11:30:50 AM
2015-12-20 11:30:50
2015-12-20 11:30:50
20-Dec-15 11:30:50 AM
20-Dec-15 11:30:50 AM
20-Dec-15 11:30:50
20-Dec-15 11:30:50

======M ========

December 20

======m ========

December 20

======O ========

2015-12-20T11:30:50.0000000

======o ========

2015-12-20T11:30:50.0000000

======R ========

Sun, 20 Dec 2015 11:30:50 GMT

======r ========

Sun, 20 Dec 2015 11:30:50 GMT

======s ========

2015-12-20T11:30:50

======t ========

11:30 AM
11:30 AM
11:30
11:30

======T ========

11:30:50 AM
11:30:50 AM
11:30:50
11:30:50

======u ========

2015-12-20 11:30:50Z

======U ========

Sunday, December 20, 2015 4:30:50 AM
Sunday, December 20, 2015 04:30:50 AM
Sunday, December 20, 2015 4:30:50
Sunday, December 20, 2015 04:30:50
December 20, 2015 4:30:50 AM
December 20, 2015 04:30:50 AM
December 20, 2015 4:30:50
December 20, 2015 04:30:50
Sunday, 20 December, 2015 4:30:50 AM
Sunday, 20 December, 2015 04:30:50 AM
Sunday, 20 December, 2015 4:30:50
Sunday, 20 December, 2015 04:30:50
20 December, 2015 4:30:50 AM
20 December, 2015 04:30:50 AM
20 December, 2015 4:30:50
20 December, 2015 04:30:50

======Y ========

December, 2015

======y ========

December, 2015

DateTime.Parse(string)

If you have a standard Date string you can easily convert it to a DateTime through  DateTime.Parse static method. Normally the date-time string that you see on the Internet is the standard format string, the MySQL database or SQL Server also use the standard format to display the date time.
// Taken from HTTP header
string httpTime = "Fri, 21 Feb 2011 03:11:31 GMT";

// Taken from w3.org
string w3Time = "2016/05/26 14:37:11";

// Taken from nytimes.com
string nyTime = "Thursday, February 26, 2012";

// Taken from ISO Standard 8601 for Dates
string isoTime = "2016-02-10";

// Taken from Windows file system Created/Modified
string windowsTime = "11/21/2015 11:35 PM";

// Taken from Windows Date and Time panel
string windowsPanelTime = "11:07:03 PM";

7- Customize datetime formats

In this session, I will guide you convert a DateTime object to string with a custom format, such as "dd/MM/yyyy", .... and vice versa.

 Customize DateTime --> string:

Using DateTime.ToString(string):
string format = "dd/MM/yyyy HH:mm:ss";

DateTime now = DateTime.Now;

// ==> 18/03/2016 23:49:39
string s = now.ToString(format);
CustomDateTimeFormatExample.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DateTimeTutorial
{
    class CustomDateTimeFormatExample
    {

        public static void Main(string[] args)
        {
            // Date format.
            string format = "dd/MM/yyyy HH:mm:ss";

            DateTime now = DateTime.Now;

            string s = now.ToString(format);

            Console.WriteLine("Now: " + s);

            Console.Read();

        }

    }

}

Customize string -> DateTime

public static DateTime Parse(string s)

public static DateTime Parse(string s, IFormatProvider provider)

public static DateTime Parse(string s, IFormatProvider provider, DateTimeStyles styles)


public static bool TryParseExact(string s, string format,
           IFormatProvider provider, DateTimeStyles style,
           out DateTime result)

public static bool TryParseExact(string s, string[] formats,
           IFormatProvider provider, DateTimeStyles style,
           out DateTime result)
Example:
Method Example
static DateTime Parse(string) // See also Standard DateTime format.
string httpHeaderTime = "Fri, 21 Feb 2011 03:11:31 GMT";
DateTime.Parse(httpHeaderTime);
static DateTime ParseExact(
  string s,
  string format,
  IFormatProvider provider
)
string dateString = "20160319 09:57";
DateTime.ParseExact(dateString ,"yyyyMMdd HH:mm",null);
static bool TryParseExact(
   string s,
   string format,
   IFormatProvider provider,
   DateTimeStyles style,
   out DateTime result
)
This method is very similar to ParseExact, but it returns a boolean, true if the time series is parsed, otherwise it returns false.
  (See example below).
ParseDateStringExample.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DateTimeTutorial
{
    class ParseDateStringExample
    {

        public static void Main(string[] args)
        {

            string dateString = "20160319 09:57";

            // Using ParseExact
            DateTime dateTime = DateTime.ParseExact(dateString, "yyyyMMdd HH:mm", null);

            Console.WriteLine("Input dateString: " + dateString);

            Console.WriteLine("Parse Results: " + dateTime.ToString("dd-MM-yyyy HH:mm:ss"));

            // Datetime string with leading white space
            dateString = "  20110319 11:57";

            // Using TryParseExact
            // The method returns true if the dateString can be parsed.
            // And return value for parameter 'out dateTime'. 
            bool successful = DateTime.TryParseExact(dateString, "yyyyMMdd HH:mm", null,
                     System.Globalization.DateTimeStyles.AllowLeadingWhite,
                     out dateTime);

            Console.WriteLine("\n------------------------\n");

            Console.WriteLine("Input dateString: " + dateString);

            Console.WriteLine("Can Parse? :" + successful);

            if (successful)
            {
                Console.WriteLine("Parse Results: " + dateTime.ToString("dd-MM-yyyy HH:mm:ss"));
            }


            Console.Read();
        }
    }

}
Running the example: