Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between UniversalSortableDateTimePattern and SortableDateTimePattern

Tags:

c#

I see there are two types of sortable datetime patterns i can format my strings on...

  1. SortableDateTimePattern outputs a value with a T in the middle between date and time
  2. UniversalSortableDateTimePattern outputs a value with a Z in the end after the time

What are the implications of each in terms of interprocess communication such as data interchange in JSON, XML or tabular data.

Is any of the two by any chance adjusted to UTC automatically? (Seems not at first look)

I've read the poor level of documentation available on MSDN regarding the two, sadly they offer no insight on this question...

like image 807
Mathieu Dumoulin Avatar asked Nov 19 '12 15:11

Mathieu Dumoulin


2 Answers

UniversalSortableDateTimePattern uses UTC. That's what the Z at the end is for.

Try this simple sample:

string s = DateTime.Now.ToString(CultureInfo.CurrentCulture.DateTimeFormat.SortableDateTimePattern);
DateTime d = DateTime.Parse(s);

Console.WriteLine(s);
Console.WriteLine(d);

Console.WriteLine();

s = DateTime.Now.ToString(CultureInfo.CurrentCulture.DateTimeFormat.UniversalSortableDateTimePattern);
d = DateTime.Parse(s);

Console.WriteLine(s);
Console.WriteLine(d);

So long as your timezone is not UTC+0, you'll notice the time is different on the second block.

My read on this would be to prefer UniversalSortableDateTimePattern when used across timezones.

like image 172
Jon B Avatar answered Oct 13 '22 08:10

Jon B


SortableDateTimePattern is culture dependent and does not include time zone offset information. UniversalSortableDateTimePattern is culture independent, the same on any computer, anywhere, and includes the time zone offset. The offset is from UTC, so adding or subtracting it from the time as appropriate will get you the UTC time. It is generally better to use UniversalSortableDateTimePattern if you will be working with multiple timezones and/or nationalities.

However, it is much simpler if you always want your time to be UTC to use the appropriate DateTime property or method before converting to a string, i.e. DateTime.UtcNow Property to get the current date and time in UTC or for an existing DateTime, the DateTime.ToUniversalTime Method.

like image 29
JamieSee Avatar answered Oct 13 '22 08:10

JamieSee