如何获取当地时区的当前日期和时间?
问题描述:
如何获取当地时区的当前日期和时间? 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
+0
对不起。不错的尝试。 – Joshua
重要的是要指出,这通过.NET 3.5证明是真实的。在.NET 4.0中更改了行为以获取DateTime.Now上的当前时区。 – Joshua