Zaheer Ahmed
Zaheer Ahmed

Reputation: 28528

DateTime Unspecified Kind

On msdn it is defined for Unspecified Kind as:

kind

So if Kind is unspecified DateTime is UTC, but on the same page (given example):

class Sample 
{
    public static void Main() 
    {
      DateTime saveNow = DateTime.Now;
      myDt = DateTime.SpecifyKind(saveNow, DateTimeKind.Unspecified);
      Display("Unspecified: .....", myDt);
    }

    public static string datePatt = @"M/d/yyyy hh:mm:ss tt";

    public static void Display(string title, DateTime inputDt)
    {
      DateTime dispDt = inputDt;
      string dtString;
    
      dtString = dispDt.ToString(datePatt);
      Console.WriteLine("{0} {1}, Kind = {2}", title, dtString, dispDt.Kind);

      dispDt = inputDt.ToLocalTime();
      dtString = dispDt.ToString(datePatt);
      Console.WriteLine("  ToLocalTime:     {0}, Kind = {1}", dtString, dispDt.Kind);

      dispDt = inputDt.ToUniversalTime();
      dtString = dispDt.ToString(datePatt);
      Console.WriteLine("  ToUniversalTime: {0}, Kind = {1}", dtString, dispDt.Kind);
      Console.WriteLine();
    }
  }
}

giving the output as:

Unspecified: ..... 5/6/2005 02:34:42 PM, Kind = Unspecified

ToLocalTime: 5/6/2005 07:34:42 AM, Kind = Local

ToUniversalTime: 5/6/2005 09:34:42 PM, Kind = Utc

So, issue I have with this is, that if Unspecified is Utc then why Utc to Utc conversion change the datetime object value?

Upvotes: 40

Views: 44925

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1500065

No, Unspecified and UTC are very different - the page you're quoting from is from ToLocalTime. The point is that if you call ToLocalTime using an "unspecified" DateTime, then the value will be treated as if it were in UTC.

Likewise if you call ToUniversalTime using an "unspecified" DateTime, then the value will be treated as if it were in the system local time zone.

Frankly this sort of thing is why I dislike DateTime rather a lot. If I were you, I'd use Noda Time instead, which separates the concepts out into different types entirely, removing a lot of the confusion. (There are more types to know about, but each one represents a single concept.) I'm clearly biased though...

Upvotes: 94

helios456
helios456

Reputation: 1644

The DateTimeKind.Unspecified is useful in cases where you don't want the time to be converted to another local time.

Take for example a server application which displays the current time for the server in a client application. If you do not specify DateTimeKind.Unspecified on the server and the current time is retrieved through a WCF call, then when .ToString is called in the client application, it will automatically be converted to the local time zone if they are different.

Upvotes: 14

Related Questions