Monday 28 September 2015

C# and UTC timestamps

DateTime values are usually stored in a local datetime format using DateTime.Now This is sufficient if your system or application only runs in a specific time zone, but storing DateTime values can be erroneous since clients can adjust their time zones. If you save the timestamps as DateTime.Now, the value will be displayed wrong for users with a different time zone. Instead, use DateTime.UtcNow After saving the time stamp as UTC to a database for example, the value must be retrieved again and displayed. This is done with the method SpecifyKind(), passing in the datetime value and setting DateTimeKind to Utc. Finally the code must use the Utc Time packed value and use the method ToLocalTime to finally get the correct timestamp. The consistent use of Utc-time for time stamps and using the SpecifyKind method together with ToLocalTime method will display the time stamp correct on all clients, regardless of their time zone. After all, if you use DateTime.UtcNow and not Datetime.Now, the value displayed will be offset regarding of your DateTimeOffSet value (+/- hours). For users in UTC+00:00 time zone, no adjustment needs to be specified, but then other users in other time zones will not be able to show the time stamp correct. To sum up:

  1. Use DateTime.UtcNow consistently for time stamps. Do not mix DateTime.Now and DateTime.UtcNow
  2. "Pack" the DateTime value using the SpecifyKind() method.
  3. Display the packed datetime value using ToLocalTime method.

//Define a static class to hold the extension method GetUtcDateTimePacked()
public static class DateTimeExtensions {
 
        /// 
        /// Packs the DateTime value packed into a new UtcTime 
        /// 
        public static DateTime GetUtcDateTimePacked(this DateTime dt)
        {
            DateTime convertedDate = DateTime.SpecifyKind(dt, DateTimeKind.Utc);
            return convertedDate;
        } 
		
}

void Main()
{	
	var sampleDt = DateTime.UtcNow; 
	Console.WriteLine(sampleDt.GetUtcDateTimePacked()); 
	Console.WriteLine(sampleDt.ToLocalTime()); 
}



The output given a UtcNow time of 28.09.2015 18:27:09 in a time zone with UTC +02:00 offset is then:
28.09.2015 16:27:09
28.09.2015 18:27:09

Note that we need to pack the datetime value and then use the ToLocalTime method. There you are - you can now use UTC DateTime values and display time stamps accross clients with different time zones. Now go code some more.
Share this article on LinkedIn.

1 comment: