如何獲取當地時區的當前日期和時間? System.DateTime.Now返回程序啓動時本地時區的當前日期和時間,這是錯誤的。的總和如何獲取當地時區的當前日期和時間?
重複:
.NET DateTime.Now returns incorrect time when time zone is changed
C# event to detect Daylight Saving or even manual time change
如何獲取當地時區的當前日期和時間? System.DateTime.Now返回程序啓動時本地時區的當前日期和時間,這是錯誤的。的總和如何獲取當地時區的當前日期和時間?
重複:
.NET DateTime.Now returns incorrect time when time zone is changed
C# event to detect Daylight Saving or even manual time change
你可以使用下面的代碼,如果你知道哪些本地時區你靶向
DateTime timeUtc = DateTime.UtcNow;
try
{
TimeZoneInfo cstZone = TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time");
DateTime cstTime = TimeZoneInfo.ConvertTimeFromUtc(timeUtc, cstZone);
Console.WriteLine("The date and time are {0} {1}.",
cstTime,
cstZone.IsDaylightSavingTime(cstTime) ?
cstZone.DaylightName : cstZone.StandardName);
}
catch (TimeZoneNotFoundException)
{
Console.WriteLine("The registry does not define the Central Standard Time zone.");
}
catch (InvalidTimeZoneException)
{
Console.WriteLine("Registry data on the Central STandard Time zone has been corrupted.");
}
欲瞭解更多信息 https://msdn.microsoft.com/en-us/library/bb397769(v=vs.110).aspx
對不起。不錯的嘗試。 – Joshua
重要的是要指出,這通過.NET 3.5證明是真實的。在.NET 4.0中更改了行爲以獲取DateTime.Now上的當前時區。 – Joshua