Convert UTC/GMT time to local time

前端 未结 11 989
情深已故
情深已故 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:05

    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_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Time 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);
    

提交回复
热议问题