Convert UTC/GMT time to local time

前端 未结 11 1003
情深已故
情深已故 2020-11-22 04:39

We are developing a C# application for a web-service client. This will run on Windows XP PC\'s.

One of the fields returned by the web service is a DateTime field. Th

11条回答
  •  灰色年华
    2020-11-22 05:13

    For strings such as 2012-09-19 01:27:30.000, DateTime.Parse cannot tell what time zone the date and time are from.

    DateTime has a Kind property, which can have one of three time zone options:

    • Unspecified
    • Local
    • Utc

    NOTE If you are wishing to represent a date/time other than UTC or your local time zone, then you should use DateTimeOffset.


    So for the code in your question:

    DateTime convertedDate = DateTime.Parse(dateStr);
    
    var kind = convertedDate.Kind; // will equal DateTimeKind.Unspecified
    

    You say you know what kind it is, so tell it.

    DateTime convertedDate = DateTime.SpecifyKind(
        DateTime.Parse(dateStr),
        DateTimeKind.Utc);
    
    var kind = convertedDate.Kind; // will equal DateTimeKind.Utc
    

    Now, once the system knows its in UTC time, you can just call ToLocalTime:

    DateTime dt = convertedDate.ToLocalTime();
    

    This will give you the result you require.

提交回复
热议问题