Convert UTC/GMT time to local time

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. The server returns a field in GMT format ie with a "Z" at the end.

However, we found that .NET seems to do some kind of implicit conversion and the time was always 12 hours out.

The following code sample resolves this to some extent in that the 12 hour difference has gone but it makes no allowance for NZ daylight saving.

CultureInfo ci = new CultureInfo("en-NZ");
string date = "Web service date".ToString("R", ci);
DateTime convertedDate = DateTime.Parse(date);            

As per this date site:

UTC/GMT Offset

Standard time zone: UTC/GMT +12 hours
Daylight saving time: +1 hour
Current time zone offset: UTC/GMT +13 hours

How do we adjust for the extra hour? Can this be done programmatically or is this some kind of setting on the PC's?


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.


    I'd look into using the System.TimeZoneInfo class if you are in .NET 3.5. See http://msdn.microsoft.com/en-us/library/system.timezoneinfo.aspx. This should take into account the daylight savings changes correctly.

    // Coordinated Universal Time string from 
    // DateTime.Now.ToUniversalTime().ToString("u");
    string date = "2009-02-25 16:13:00Z"; 
    // Local .NET timeZone.
    DateTime localDateTime = DateTime.Parse(date); 
    DateTime utcDateTime = localDateTime.ToUniversalTime();
    
    // ID from: 
    // "HKEY_LOCAL_MACHINESoftwareMicrosoftWindows NTCurrentVersionTime Zone"
    // See http://msdn.microsoft.com/en-us/library/system.timezoneinfo.id.aspx
    string nzTimeZoneKey = "New Zealand Standard Time";
    TimeZoneInfo nzTimeZone = TimeZoneInfo.FindSystemTimeZoneById(nzTimeZoneKey);
    DateTime nzDateTime = TimeZoneInfo.ConvertTimeFromUtc(utcDateTime, nzTimeZone);
    

    TimeZone.CurrentTimeZone.ToLocalTime(date);
    
    链接地址: http://www.djcxy.com/p/18756.html

    上一篇: 如何在python中感知不知道的日期时间时区

    下一篇: 将UTC / GMT时间转换为本地时间