How to Use the DateTime C# Structure To Work With Time

datetime c#There never seems to be enough time these days, especially if you are a programmer. You got deadlines to meet. You got bills to pay. You have documents to timestamp. Every time you look around, you must deal with time in some way. Fortunately, you can use the DateTime C# object to keep track of the time within your programs. The DateTime structure handles all your time related tasks. We use it to deal with dates, times, or both.

Learn about how to use the .Net Framework with C# at Udemy.com

The DateTime Object

Programmers coming in from other languages often find the DateTime C# class confusing at first. It is not actually a part of the C# language itself. DateTime comes from the .Net Framework through the System namespace. Because of this, many date and time functions you see in other programming languages do not exist in C#. Fortunately, DateTIme is a very robust structure that can handle any date and time between 12:00:00 Midnight on January 1, 0001 and 11:59:59 PM on December 31, 9999.

You use the DateTime structure by invoking the new keyword with your desired DateTIme constructor and storing the result in a DateTime object. Your DateTIme object can have a Date, Time, Localization, culture, milliseconds, and kind.  There are six DateTime constructors. Your program’s requirements will determine which constructor you need to use.

  • DateTime from date and time
DateTime dob = new DateTime(1974, 7, 10, 7, 10, 24);
  • DateTime from a String
DateTime dateFromString =   DateTime.Parse("7/10/1974 7:10:24 AM";);
  • Empty DateTime
DateTime emptyDateTime = new DateTime();
  • Just a Sate
DateTime justDate = new DateTime(2002, 10, 18);
  • DateTime from Ticks
DateTime justTime = new DateTime(1000000);
  • DateTime with localization
DateTime dateTimeWithKind = new DateTime(1974, 7, 10, 7, 10, 24, DateTimeKind.Local);
  • DateTime with date, time and milliseconds
DateTime dateTimeWithMilliseconds = new DateTime(2010, 12, 15, 5, 30, 45, 100);

Using Your DateTime Object

 

Once you have created a DateTime object, you can use its properties and methods to read and manipulate the date. Some of these properties are self-explanatory including Hour, Minute, Second, Millisecond, Year, Month, and Day.

Some other commonly used properties include:

  • DayOfWeek – returns the name of the day in a week.
  • DayOfYear – returns the day of a year.
  • TimeOfDay – returns the current time.
  • Today – returns the current date with midnight set as the time.
  • Now – returns the current date and time.
  • UtcNow – returns a DateTime in Coordinated Universal Time (UTC)
  • Kind – returns if the DateTime object is based on local time, UTC, or neither.
DateTime dob = new DateTime(1974, 7, 10, 7, 10, 24);

Console.WriteLine("Day:{0}", dob.Day);

Console.WriteLine("Month:{0}", dob.Month);

Console.WriteLine("Year:{0}", dob.Year);

Console.WriteLine("Hour:{0}", dob.Hour);

Console.WriteLine("Minute:{0}", dob.Minute);

Console.WriteLine("Second:{0}", dob.Second);

Console.WriteLine("Millisecond:{0}", dob.Millisecond);

Learn how to create and use objects in C#

Adding and Subtracting Dates and Times

 

Because dates and times are considered objects in C#, you will need to use DateTime methods to manipulate them. DateTime lets you add years, days, hours, minutes, seconds, milliseconds and ticks. There is no way to subject from a DateTime, though you can get the same effect by adding a negative value. For example:

aDay.AddYears(2);   // adds 2 years

aDay.AddDays(-12); //subtracts 12 days

aDay.AddHours(4.25);  // adds 4 hours and 15 minutes

Comparing Dates and Times

 

Besides these date and time manipulating methods, the DateTime structure includes a few static methods that let you compare dates and times. The simplest is IsLeapYear () which tells you if a year is a leap year or not.

DateTime.IsLeapYear(dob.Year)

While IsLeapYear () can tell you if there is a Feburary 29th, you can use the compare and CompareTo methods to compare two DateTime values. Both methods produce the same result. Both of them will return a negative number, positive number, or 0 depending if the first DateTIme is newer, later, or if both objects are the same.

DateTime firstDate = new DateTime(2002, 10, 22);

DateTime secondDate = new DateTime(2009, 8, 11);

int result = DateTime.Compare(firstDate, secondDate);

int compareResult = firstDate.CompareTo(secondDate);

Formatting DateTime C# Values

Now you have a DateTIme value, it is time to display it. You display DateTime values using the ToString() method. ToString() takes a string as an argument that represents the display formatting pattern.

myDate.ToString();

myDate.ToString(“m d, Y”);

If you do not specify the formatting pattern, DateTime uses the default full date time pattern that comes with your compiler. The format pattern is there so you can specify how you want your DateTime value to be displayed.  You can use any character you want in the format pattern though you must use the following codes to insert DateTime values into the pattern. If you need your date and time displayed in a certain way, you write it out in the pattern.

 

CodePattern
“d”Sort date
“D”Long date
“f”Full date time. Short time.
“F”Full date time. Long time.
“g”Generate 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

 

 

If this all seems too complicated, you are in luck. You don’t have to use the above codes to format your DateTime. DateTime comes with a few methods that will display your date and time in a number of standard formats. These methods are ToBinary(), ToFileTime(), ToLocalTime(), ToLongDateString(), ToLongTimeString(), ToOADate(), ToShortDateString(), ToShortTimeString(), and ToUniversalTime().They are all pretty much self-explainatory, and you use them in place of ToString(). However, you will need to use ToString() and its formatting codes if you need to customize how you want your date and time values displayed.

This is just the Beginning

I hope this article helps you get started with how to use the DateTime C# structure in your programs. I tried to include as much information as I could, but I could not fit everything there is to know about DateTime in this one article. The properties and methods I have included here are the most common ones you will use in most of your programming career. There are many others, and a recommend that you take a course in C# right here at Udemy to fully grasp the power of the DateTime C# Structure.

Learn more about C# and the .Net Framework at Udemy.com