C# Variables - Dates and Times

Almost every application you will write will need to work with dates, times, or both. Dates are used to track changes, calculate ages, and determine accessibility to content. Time spans track the duration of actions, differences between dates, and time until something expires or renews. The ability to track and manipulate dates and times is essential for any developer.


DateTime

If you want to store text values, you use a string datatype. To store a numeric value, you use an integral or floating-point datatype. What if you want to store an instant in time? For that, you would use the System.DateTime object. A DateTime variable can be used to store dates and times from 01/01/0001 12:00:00 AM to 12/31/9999 11:59:59 PM.


Coordinated Universal Time (UTC)

When working with DateTime variables, it is essential to know what UTC is and why it is used. Unlike GMT, UTC is not a time zone. It is a twenty-four-hour time standard used across the world. It is the basis for time zones around the world, but it is not officially used anywhere as a local time. Even though GMT and UTC share the same time, it is vital to know the distinction between the two.


GMT is a time zone, UTC is a timing standard.


When deciding whether to use UTC or local time, the purpose of the date needs to be considered. Local time is best used for user displays and interfaces. UTC should be used when calculating, comparing, or storing dates and times. This practice ensures that users see the same information regardless of their local time zone.


Declaration and Initialization

To declare a variable with the DateTime data type, you use the DateTime object.

 DateTime myBirtday;
 DateTime graduationDay;
 DateTime christmas;

You cannot use a literal date value to initialize the variable. If you want to provide a date at the time of initialization, you will have to use the DateTime constructor. A “constructor” is a method used to create an instance of a new object.


DateTime Constructor

The constructor for the DateTime object has a few different ways to create a new date. These different ways are called constructor overloads.

 DateTime myBirtday = new DateTime(2000, 1, 23);
 DateTime graduationDay = new DateTime(2020, 6, 30, 12, 30, 00);

The second line creates a value of 06/30/2020 12:30:00 PM. The first line of code creates a date value of 01/23/2000. If you don’t provide a time when you create a new DateTime value the time will default to 12:00:00 AM

Variable Assignment

DateTime values can also be set by using another variable as long as that variable also has a DataTime data type.

 DateTime myBirtday = new DateTime(2000, 1, 23);
 DateTime bestDayEver = myBirtday;

Computed Values

The DateTime object has a few values that it will compute for you automatically. It is common to use these when initialing variables.

  • Now – The current date and time of the computer executing the code. This value is represented as the local time.

  • UtcNow – The current date and time of the computer that is executing the code. This value is represented as the Coordinated Univeral Time (UTC).

  • Today – The current date of the computer executing the code. The time is set to 00:00:00

 DateTime today = DateTime.Today;
 DateTime currentTime = DateTime.Now;
 DateTime currrentUtcTime = DateTime.UtcNow;

DateTime Properties

The DateTime object has many properties that allow you to work with the date and time value of your variable.


Date/TimeOfDay – Date gets the date value of the variable, setting the time value to 00:00:00. Time returns the time of day.

 DateTime today = DateTime.Now;
  DateTime currentDate = today.Date; 
  DateTime currentTime = today.TimeOfDay;

Month/Day/Year – Gets the integer value of the property you are requesting.

 int currentMonth = today.Month;
 int currentDay = today.Day;
 int currentYear = today.Year;

DayOfWeek/DayOfYear – Day of the week will get the string representation of the day for the date value (e.g., Wednesday). DayOfYear will return the integer value representing the day of the year.

 Console.WriteLine(today.DayOfWeek); // Displays "Wednesday"
 Console.WriteLine(today.DayOfYear); // Displays 118

Hour/Minute/Second – Gets the integer value of the property you are requesting.

 int currentHour = today.Hour;
 int currentMinute = today.Minute;
 int currentSecond = today.Second;

Ticks – Gets the number of Ticks that represent the specified DateTime value. More detail on Ticks can found in the TimeSpan section of this post.


DateTime Methods

In addition to the properties discussed earlier, the DateTime method has many that aid you when working with data and time values. This blog covers some of the more common ones.


AddDays/AddMonths/AddYears – These methods will return a new DateTime value that adds the provided number to the property you specified.

Console.WriteLine($"In 4 years the date will be {today.AddYears(4)}.");
Console.WriteLine($"In 72 months the date will be {today.AddMonths(72)}.");
Console.WriteLine($"In 212 days the date will be {today.AddDays(212)}.");

AddHours/AddMinutes/AddSeconds – These methods will return a new DateTime value that adds the provided number to the property you specified.

Console.WriteLine($"When I'm done reading this blog it will be {today.AddMinutes(10)}.");
Console.WriteLine($"But it feel more like {today.AddHours(2)}.");
Console.WriteLine($"I wish I could be a DateTime expert by {today.AddSeconds(45)}.");

Subtract – This method is used to subtract one date from another to determine the difference between the two dates. Subtract returns a TimeSpan value that stores that difference. The TimeSpan object is discussed later in this post.


CompareTo – The method will compare the DateTime value to a second value that you provide and return an integer indicating if the variable value is earlier than (-1), equal to (0), or later than the second value(1).


 DateTime lastWeek = today.AddDays(-7);
 DateTime nextWeek = today.AddDays(7);
 Console.WriteLine(today.CompareTo(today));
 Console.WriteLine(today.CompareTo(lastWeek));
  Console.WriteLine(today.CompareTo(nextWeek));

When this code is executed, the display will show:

0

-1

1 ToLocalTime/ToUniversalTime – These methods will convert a DateTime value from UTC to a local time value or from local time to a UTC value.


Parse/TryParse - Parse and TryParse are two methods that exist for all numeric data types. These methods are used to aid in the conversion of value to that particular datatype.


Parse is covered in the blog regarding converting between types.


TryParse is covered in the blog covering conditional logic.


DateTime ToString Methods

The standard ToString method will display your DateTime value precisely as it is stored in the variable.

 Console.WriteLine(today.ToString());

However, there are other ways you may want to display the value. Luckily the DateTime object comes with some methods to help you display your information in the more standard ways.


ToLongDateString – Displays the extended date representation of the value (“Tuesday, April 21, 2020”).


ToShortDateString – Displays the abbreviated date representation of the value (“4/21/2020”).

ToLongTimeString – Displays the extended time representation of the value (“10:53:56 PM”).

ToShortTimeString – Displays the abbreviated time representation of the value (“10:53 PM”).


TimeSpan

A timespan is an interval of time that has occurred between two dates. C# determines timespan with a unit of measurement called a “tick,” which equates to 100 nanoseconds. A timespan is represented by the number of ticks that have occurred between two DateTime values.


Declaration and Initialization

To declare a variable with the TimeSpan data type, you use the TimeSpan object.

 TimeSpan daysUntilBirthday;
 TimeSpan daysUntilGraduation;
 TimeSpan daysUntilChristmas;

TimeSpan Constructor

You can use the constructor for the TimeSpan object to initialize a variable. The TimeSpan has constructor overloads similar to a DateTime object.

 TimeSpan ticksInASecond = new TimeSpan(0, 0, 1);
 TimeSpan ticksInAMinute = new TimeSpan(0, 1, 0);
 TimeSpan ticksInAnHour = new TimeSpan(1, 0, 0);
 TimeSpan ticksInADay = new TimeSpan(1,0,0,0);

Normally, TimeSpan variables are not initialized in this manner. Their values are usually set by performing a date comparison.


Variable Assignment

The TimeSpan variable will store the number of ticks that occur between two dates. The value can be positive or negative.

 DateTime myBirtday = new DateTime(2000, 1, 23);
 DateTime sonBirthday = new DateTime(2008, 3, 14);
 DateTime christmas = new DateTime(2020, 12, 25);
 DateTime graduationDay = new DateTime(2020, 6, 30, 12, 30, 00);
 
 int daysGraduationPostponed = 37;
 
 TimeSpan ticksBetweenBirthdays = myBirtday - sonBirthday;
 TimeSpan ticksUntilChristmas = christmas - DateTime.Now;
 TimeSpan ticksUntilGraduation = graduationDay.AddDays(daysGraduationPostponed) - DateTime.Now;

TimeSpan Properties

Once you have the number of ticks captured in a variable, you can use the properties of the TimeSpan object to represent those ticks in any fashion your application needs. You can convert the ticks to days, hours, minutes, seconds, or milliseconds.

 int ageDifferernceInYears = ticksBetweenBirthdays.Days / 365;
 int hoursUntilChristmas = ticksUntilChristmas.Hours;
 int secondsUntilGraduation = ticksUntilGraduation.Seconds;

70 views1 comment

Recent Posts

See All