如何获取特定时区的DateTime.Now,而不受设备时区影响?

25
我有一个使用MonoTouch开发的应用程序,该应用程序从Web服务中处理数据。该数据包含特定于时区的日期信息。该时区是UTC +12,适用于新西兰。
我的应用程序基于当前时间显示此数据。问题在于当应用程序在不同的时区使用时,由于设备上的当前时间不正确,因此数据显示不正确。
我如何获取UTC +12的当前日期和时间,而不考虑设备上的语言环境/时区设置?
编辑:
我已尝试了下面答案中提供的代码:
TimeZoneInfo.ConvertTime (DateTime.Now, TimeZoneInfo.FindSystemTimeZoneById("Pacific/Auckland"));

这段代码在我的电脑上能正常工作,但是当我在MonoTouch上运行时,会出现以下异常:

System.ArgumentException: Kind propery of dateTime is Local but the sourceTimeZone does not equal TimeZoneInfo.Local
   at System.TimeZoneInfo.ConvertTime (DateTime dateTime, System.TimeZoneInfo sourceTimeZone, System.TimeZoneInfo destinationTimeZone) [0x00018] in /Developer/MonoTouch/Source/mono/mcs/class/System.Core/System/TimeZoneInfo.cs:179
   at System.TimeZoneInfo.ConvertTime (DateTime dateTime, System.TimeZoneInfo destinationTimeZone) [0x00000] in /Developer/MonoTouch/Source/mono/mcs/class/System.Core/System/TimeZoneInfo.cs:173

@lanks:发生了什么?为什么你取消了你的回答。不是你想要的吗? - Nikhil Agrawal
@Nickhil Agrawal 抱歉,经过测试您的答案不起作用。我已经更新了我的问题,其中包括代码和异常信息。 - startupsmith
3个回答

56

使用DateTime.Now。这将给您系统时区的日期和时间。现在像这样将该时间转换为所需的时区时间。

var indianTime = TimeZoneInfo.ConvertTime (DateTime.Now,
                 TimeZoneInfo.FindSystemTimeZoneById("India Standard Time"));

要获取时区列表,请运行此方法。

ReadOnlyCollection<TimeZoneInfo> zones = TimeZoneInfo.GetSystemTimeZones();
Console.WriteLine("The local system has the following {0} time zones", zones.Count);
foreach (TimeZoneInfo zone in zones)
    Console.WriteLine(zone.Id);

6
微软时区列表:https://msdn.microsoft.com/zh-cn/library/ms912391(v=winembedded.11).aspx - RJB

14

你可以这样做:

Datetime date = TimeZoneInfo.ConvertTime(utcDateTime, timeZone); 

只需传递给定的参数即可。


3

这是MonoTouch中的错误

修复将包含在未来版本的MonoTouch中(但我不确定具体是哪个版本)。

无论如何,已经有热补丁可用。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接