- Use DateTime.UtcNow consistently for time stamps. Do not mix DateTime.Now and DateTime.UtcNow
 - "Pack" the DateTime value using the SpecifyKind() method.
 - 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.
great
ReplyDelete