c# – 使用Nodatime将UTC时间转换为本地时间

我已经提供了这种格式“ddMMyyHHmmss”的时间.我知道时间是UTC格式.我想使用NodaTime库将其转换为我当地的时区,但我似乎无法弄明白.我当地的时区目标是新西兰.

这是我尝试过的:

var pattern = LocalDateTimePattern.CreateWithInvariantCulture("ddMMyyHHmmss");

 var parseResult = pattern.Parse(utcDateTime);
 if (!parseResult.Success)
 {
     throw new InvalidDataException("Invalid time specified " + date + time);
 }

 var timeZone = DateTimeZoneProviders.Bcl["New Zealand Standard Time"];

 var zone = new zoneddatetime(
                  localDateTime,timeZone,timeZone.GetUtcOffset(SystemClock.Instance.Now));


 return new DateTime(zone.ToInstant().Ticks);

解决方法

// Since your input value is in UTC,parse it directly as an Instant.
var pattern = InstantPattern.CreateWithInvariantCulture("ddMMyyHHmmss");
var parseResult = pattern.Parse("150713192900");
if (!parseResult.Success)
    throw new InvalidDataException("...whatever...");
var instant = parseResult.Value;

Debug.WriteLine(instant);  // 2013-07-15T19:29:00Z

// You will always be better off with the tzdb,but either of these will work.
var timeZone = DateTimeZoneProviders.Tzdb["Pacific/Auckland"];
//var timeZone = DateTimeZoneProviders.Bcl["New Zealand Standard Time"];

// Convert the instant to the zone's local time
var zoneddatetime = instant.InZone(timeZone);

Debug.WriteLine(zoneddatetime);
  // Local: 7/16/2013 7:29:00 AM Offset: +12 Zone: Pacific/Auckland

// and if you must have a DateTime,get it like this
var bclDateTime = zoneddatetime.ToDateTimeUnspecified();

Debug.WriteLine(bclDateTime.ToString("o"));  // 2013-07-16T07:29:00.0000000

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...