Working with DateTime data type in C#

Ksuresh
Posted by in C# category on for Beginner level | Points: 250 | Views : 29305 red flag

In this article we are going to learn DateTime data type, its methods and properties.

DateTime

 

This DateTime data type represents an instance in time, typically expressed as a date and time of day.

 

So first let’s learn about the default constructors of DateTime.

Constractor Name Description
DateTime(ticks) This constructor initializes a new instance of the DateTime structure to a specified number of ticks.
DateTime(year, month, day) This constructor initializes a new instance of the DateTime structure to the specified year, month, and day.
DateTime(year, month, day, Calendar) This constructor initializes a new instance of the DateTime structure to the specified year, month, and day for the specified calendar.
DateTime(year, month, day, hour, minute, second) This constructor initializes a new instance of the DateTime structure to the specified year, month, day, hour, minute, and second.
DateTime(year, month, day, hour, minute, second, Calendar) This constructor initializes a new instance of the DateTime structure to the specified year, month, day, hour, minute, and second for the specified calendar.
DateTime(year, month, day, hour, minute, second, millisecond) This constructor initializes a new instance of the DateTime structure to the specified year, month, day, hour, minute, second, and millisecond
DateTime(year, month, day, hour, minute, second, millisecond, Calendar) This constructor initializes a new instance of the DateTime structure to the specified year, month, day, hour, minute, second, and millisecond for the specified calendar.

Example:

using System;

using System.Globalization;

class datetime

{

    public static void Main()

    {

      DateTime dt = new DateTime();

      DateTime dt1 = new DateTime(600);

      DateTime dt2 = new DateTime(2011,08,4);

      DateTime dt3 = new DateTime(2011,08,19,20,08,30);

      DateTime dt4 = new DateTime(2011,08,4,4,09,20,200);


      // here we are creating the object of julianCalender and some other calenders persiancalender, HijriCalendar. 

     JulianCalendar calendar = new JulianCalendar();

      DateTime dt5 = new DateTime(2011, 08, 04, calendar);

     Console.WriteLine(dt);

     Console.WriteLine("this specifies no of ticks"+dt1.Ticks);

     Console.WriteLine("this intializes year,month,day"+dt2);

    Console.WriteLine("this intializes year,month,day,hour,minute,second"+dt3);

    Console.WriteLine("this intialize year,month,day,hour,minute,second,milliseconds" + dt4);

    Console.WriteLine("julian calender: "+dt5);

   

    }   

}

Output:


Let us learn about the DateTime properties with an example.

DateTime Properties:

Property Nmae Description
 Date Gets the date component of this instance.
 Day Gets the day of the month represented by this instance.
DayOfWeek Gets the day of the week represented by this instance.
 DayOfYear Gets the day of the year represented by this instance.
Hour Gets the hour component of the date represented by this instance.
 Kind Gets a value that indicates whether the time represented by this instance is based on local time, Coordinated Universal Time (UTC), or neither.
 Millisecond Gets the milliseconds component of the date represented by this instance.
 Minute Gets the minute component of the date represented by this instance.
Month Gets the month component of the date represented by this instance.
Now Gets a DateTime object that is set to the current date and time on this computer, expressed as the local time.
Second Gets the seconds component of the date represented by this instance.
Ticks Gets the number of ticks that represent the date and time of this instance.
TimeOfDay Gets the time of day for this instance.
Today Gets the current date.
UtcNow Gets a DateTime object that is set to the current date and time on this computer, expressed as the Coordinated Universal Time (UTC).
Year Gets the year component of the date represented by this instance.

In below code snippet I am going to demonstrate the properties of the DateTime, for easy understandability I have written the purpose of each property as comment in the code.

Example:

using System;

class datetime

{

    public static void Main()

    {

 

        //specific reperesentation of Date Time

        DateTime dt = new DateTime(2011, 08, 4, 4, 09, 20, 200);

        //Gets a DateTime object that is set to the current date and time on this computer, expressed as the local time.

        DateTime now = DateTime.Now;

        //Gets the current date.

        DateTime today = DateTime.Today;

       

        Console.WriteLine("======================");

        Console.WriteLine("For secified Date Time:");

        //Gets the year component of the specified date time.

        Console.WriteLine("Year: " + dt.Year);

        //Gets the month component of the specified date time.

        Console.WriteLine("Month: " + dt.Month);

 

        //Gets the hour component of the specified date time.

        Console.WriteLine("Hours: " + dt.Hour);

        //Gets the minute component of the specified date time.

        Console.WriteLine("Minutes: " + dt.Minute);

        //Gets the seconds component of the specified date time.

        Console.WriteLine("Seconds: " + dt.Second);

        //Gets the milliseconds component of the specified date time.

        Console.WriteLine("Milliseconds: " + dt.Millisecond);

        //Gets the date component of the specified date time.

        Console.WriteLine("Date: " + dt.Date);

        //Gets the day of the month represented by specified date time.

        Console.WriteLine("Day: " + dt.Day);

        //Gets the day of the week represented by specified date time.

        Console.WriteLine("Day of week: " + dt.DayOfWeek);

        //Gets the day of the year represented by specified date time

        Console.WriteLine("Day of year: " + dt.DayOfYear);

        //Gets the number of ticks that represent specified date time.

        Console.WriteLine("Ticks: " + dt.Ticks);

        //Gets the time of day for specified date time

        Console.WriteLine("Time of the day: " + dt.TimeOfDay);

        Console.WriteLine("======================");

        Console.WriteLine("For Current Date Time:");

        Console.WriteLine(now);

        //Gets the year component of the specified date time.

        Console.WriteLine("Year: " + now.Year);

        //Gets the month component of the specified date time.

        Console.WriteLine("Month: " + now.Month);

        //Gets the day of the month represented by specified date time.

        Console.WriteLine("Day: " + now.Day);

        //Gets the hour component of the specified date time.

        Console.WriteLine("Hours: " + now.Hour);

        //Gets the minute component of the specified date time.

        Console.WriteLine("Minutes: " + now.Minute);

        //Gets the seconds component of the specified date time.

        Console.WriteLine("Seconds: " + now.Second);

        //Gets the milliseconds component of the specified date time.

        Console.WriteLine("Milliseconds: " + now.Millisecond);

        //Gets the date component of the specified date time.

        Console.WriteLine("Date: " + now.Date);

        //Gets the day of the week represented by specified date time.

        Console.WriteLine("Day of week: " + now.DayOfWeek);

        //Gets the day of the year represented by specified date time

        Console.WriteLine("Day of year: " + now.DayOfYear);

        //Gets the number of ticks that represent specified date time.

        Console.WriteLine("Ticks: " + now.Ticks);

        //Gets the time of day for specified date time

        Console.WriteLine("Time of the day: " + dt.TimeOfDay);

        Console.WriteLine("today: " + today);

 

    }

 

} 

When we run the above code, it looks something like this

Output

Let us learn about the DateTime Methodas with an example.

Date Time Methods

Method Name Description
Add Returns a new DateTime that adds the value of the specified TimeSpan to the value of this instance.
AddDays  Returns a new DateTime that adds the specified number of days to the value of this instance.
AddHours  Returns a new DateTime that adds the specified number of hours to the value of this instance
AddMilliseconds Returns a new DateTime that adds the specified number of milliseconds to the value of this instance.
AddMinutes Returns a new DateTime that adds the specified number of minutes to the value of this instance.
AddMonths  Returns a new DateTime that adds the specified number of months to the value of this instance.
AddSeconds Returns a new DateTime that adds the specified number of seconds to the value of this
AddTicks                  Returns a new DateTime that adds the specified number of ticks to the value of this instance.
AddYears        Returns a new DateTime that adds the specified number of years to the value of this instance.
Compare   Compares two instances of DateTime and returns an integer that indicates whether the first instance is earlier than, the same as, or later than the second instance. 
CompareToDateTime)        Compares the value of this instance to a specified DateTime value and returns an integer that indicates whether this instance is earlier than, the same as, or later than the specified DateTime value.
CompareTo(Object)  Compares the value of this instance to a specified object that contains a specified DateTime value, and returns an integer that indicates whether this instance is earlier than, the same   as or later than the specified DateTime value.
DaysInMonth Returns the number of days in the specified month and year.
Equals(DateTime)   Returns a value indicating whether this instance is equal to the specified DateTime instance.
Equals(Object)  Returns a value indicating whether this instance is equal to a specified object. (Overrides ValueType.Equals(Object).
 Equals(DateTime, DateTime)  Returns a value indicating whether two instances of DateTime are equal.
 Finalize   Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
 FromBinary  Deserializes a 64-bit binary value and recreates an original serialized DateTime object.
 FromFileTime  Converts the specified Windows file time to an equivalent local time. 
 FromFileTimeUtc  Converts the specified Windows file time to an equivalent UTC time.
FromOADate  Returns a DateTime equivalent to the specified OLE Automation Date
GetDateTimeFormats() Converts the value of this instance to all the string representations supported by the standard date and time format specifiers..
GetDateTimeFormats(Char) Converts the value of this instance to all the string representations supported by the specified standard date and time format specifier.
GetHashCode Returns the hash code for this instance. (Overrides ValueType.GetHashCode().)
GetType   Gets the Type of the current instance. (Inherited from Object.)
GetTypeCode  Returns the Type Code for value type DateTime.
IsDaylightSavingTime Indicates whether this instance of DateTime is within the daylight saving time range for the current time zone.
 IsLeapYear  Returns an indication whether the specified year is a leap year.

Parse(String)             

Converts the specified string representation of a date and time to its DateTime equivalent.
SpecifyKind Creates a new DateTime object that has the same number of ticks as the specified DateTime, but is designated as either local time, Coordinated Universal Time (UTC), or neither, as indicated by the specified DateTimeKind value.
Subtract(DateTime) It is used to subtract the specified date and time from this instance of the DateTime object.
Subtract(TimeSpan) Subtracts the specified duration from this instance.
ToBinary Serializes the current DateTime object to a 64-bit binary value that subsequently can be used to recreate the DateTime object.
ToFileTime  Converts the value of the current DateTime object to a Windows file time.
ToFileTimeUtc Converts the value of the current DateTime object to a Windows file time.
ToLocalTime Converts the value of the current DateTime object to local time.
ToLongDateString Converts the value of the current DateTime object to its equivalent long date string representation.
ToLongTimeString Converts the value of the current DateTime object to its equivalent long time string representation.
ToOADate  Converts the value of this instance to the equivalent OLE Automation date.
ToShortDateString Converts the value of the current DateTime object to its equivalent short date string representation.
ToShortTimeString Converts the value of the current DateTime object to its equivalent short time string representation.
ToString()  Converts the value of the current DateTime object to its equivalent string representation. (Overrides ValueType.ToString().)
ToString(String) Converts the value of the current DateTime object to its equivalent string representation using the specified format.
ToUniversalTime Converts the value of the current DateTime object to Coordinated Universal Time (UTC).
TryParse(String, DateTime) Converts the specified string representation of a date and time to its DateTime equivalent and returns a value that indicates whether the conversion succeeded.

In below code snippet I am going to demonstrate the methods of the DateTime, for easy understandability I have written the purpose of each method as comment in the code.

Example:

using System;

class datetime

{

    public static void Main()

    {

        // intialization of time span

        TimeSpan value = new TimeSpan();

        //providing time span value interms of no.of Ticks, A single tick represents one hundred nanoseconds or one ten-millionth of a second. There are 10,000 ticks in a millisecond

        TimeSpan timespan = new TimeSpan(12456);

        //providing time span value in terms of hours, minutes, and seconds.

        TimeSpan timespan1 = new TimeSpan(23, 55, 50);

        //providing time span value in the format of days,hours,minutes,seconds.

        TimeSpan timespan2 = new TimeSpan(2, 10, 30, 20);

        //providing time span value in the format of days,hours,minutes,seconds,milliseconds.

        TimeSpan timespan3 = new TimeSpan(1, 0, 45, 26, 70);

 

        //specific reperesentation of Date Time

        DateTime dt = new DateTime(2011, 08, 4, 4, 09, 20, 200);

        //Gets a DateTime object that is set to the current date and time on this computer, expressed as the local time.

        DateTime now = DateTime.Now;

        //cheks weather given year is leap year or not

        bool leapyear = DateTime.IsLeapYear(2004);

        Console.WriteLine("=========================================");

        Console.WriteLine(value);

        //adds specified  timespan value to the current date time.

        Console.WriteLine("adding the timespan value: " + now.Add(timespan1));

        //this method adds no of Days to the current date time

        Console.WriteLine("addition of days: " + now.AddDays(2));

        //this method adds no of hours to the current date time.

        Console.WriteLine("addition of hours: " + now.AddHours(6));

        // this adds minutes to current date time.

        Console.WriteLine("addition of minutes: " + now.AddMinutes(30));

        //this adds no of seconds the current date time .

        Console.WriteLine("addition of seconds: " + now.AddSeconds(45));

        //this method adds miliseconds to current date time.

        Console.WriteLine("addtion of milliseconds: " + now.AddMilliseconds(100));

        //this adds no of months to current date time

        Console.WriteLine("addtion of months: " + now.AddMonths(3));

        // this method adds no: of years to current date time

        Console.WriteLine("addtin of years: " + now.AddYears(2));

        //this method compares the two date time values.

        Console.WriteLine("comparing date times: " + now.CompareTo(dt));

        //this cheks given  date time values are equal or not.

        Console.WriteLine("checking date times for equal or not: " + now.Equals(now));

        //this gives formats of current date time

        Console.WriteLine("Get format of dae time: " + now.GetDateTimeFormats());

        Console.WriteLine("This gives hashcode:" + now.GetHashCode());

        //Indicates whether this instance of DateTime is within the daylight saving time range for the current time zone.

        Console.WriteLine("is Day light saving time:" + now.IsDaylightSavingTime());

        //this method subracts date times values.

        Console.WriteLine("subtractin of date time: " + dt.Subtract(timespan1));

        //Serializes the current DateTime object to a 64-bit binary value that subsequently can be used to recreate the DateTime object.

        Console.WriteLine("binary value:"+now.ToBinary());

        // it gives file time,Represents the number of 100-nanosecond intervals since January 1, 1601. This structure is a 64-bit value.

        Console.WriteLine("File Time=" + dt.ToFileTime());

        Console.WriteLine(now.ToOADate());

        Console.WriteLine(now.ToShortDateString());

        Console.WriteLine(now.ToShortTimeString());

        Console.WriteLine("is leap year: " + leapyear);

    }

 

}

 

When we run the above code, it looks something like this

Output:


In case you have missed my  articles in this series, read - C# Fundamentals, DataTypes in C#.

Hope this article was useful. Do let me know your comment or feedback.

In case you want to learn ASP.NET with Tips and Tricks, I found .NET Tips and Tricks very useful.

Reference: 

  1. I have taken reference of the C# 4.0 Complete reference book that I am going through these days.
  2. http:// msdn.microsoft.com/en-us/library/system.datetime.aspx


Page copy protected against web site content infringement by Copyscape

About the Author

Ksuresh
Full Name: suresh reddy
Member Level: Starter
Member Status: Member
Member Since: 3/24/2011 3:29:04 AM
Country: India

http://www.dotnetfunda.com

Login to vote for this post.

Comments or Responses

Posted by: Nithadeepak on: 8/11/2011 | Points: 25
Very informative....
Thanks for the article...

Login to post response

Comment using Facebook(Author doesn't get notification)