无论设备时区如何,都可以获取特定TimeZone的DateTime.Now?

sta*_*ith 9 .net c# mono xamarin.ios

我有MonoTouch应用程序,它处理来自Web服务的数据.该数据包含特定于时区的日期信息.时区为UTC +12,适用于新西兰.

我的应用程序根据当前时间显示此数据.这个问题是当应用程序在不同的时区使用时,数据无法正确显示,因为设备上的当前时间不正确.

无论设备上的区域设置/时区设置如何,如何获取UTC +12的当前日期时间?

编辑:

我根据以下答案尝试了以下代码:

TimeZoneInfo.ConvertTime (DateTime.Now, TimeZoneInfo.FindSystemTimeZoneById("Pacific/Auckland"));
Run Code Online (Sandbox Code Playgroud)

这段代码在我的电脑上工作正常但是当我在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
Run Code Online (Sandbox Code Playgroud)

Nik*_*wal 29

使用DateTime.Now.这将为您提供系统TimeZone日期和时间.现在将这个时间转换为所需的时区时间

var indianTime = TimeZoneInfo.ConvertTime (DateTime.Now,
                 TimeZoneInfo.FindSystemTimeZoneById("India Standard Time"));
Run Code Online (Sandbox Code Playgroud)

要获取TimeZone列表,请运行此方法

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);
Run Code Online (Sandbox Code Playgroud)

  • MSFT时区列表:https://msdn.microsoft.com/en-us/library/ms912391(v = winembedded.11).aspx (4认同)

Err*_*Efe 11

你可以这样做:

Datetime date = TimeZoneInfo.ConvertTime(utcDateTime, timeZone); 
Run Code Online (Sandbox Code Playgroud)

只需传递给定的参数.


Rol*_*nge 3

这是 MonoTouch 中的一个错误

该修复将包含在 MonoTouch 的未来版本中(不过我还不知道具体是哪个)。

无论如何,已经有一个可用的修补程序