2013-07-16 298 views
6

我已經以這種格式「ddMMyyHHmmss」提供了一段時間。我知道時間是UTC格式。我想使用NodaTime庫將其轉換爲我當地的時區,但我似乎無法弄清楚。我當地的時區目標是新西蘭。使用Nodatime將UTC時間轉換爲本地時間

這是我曾嘗試:

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); 

回答

14
// 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 
+0

真棒感謝,我給它一個去 – dreza

+0

工作一種享受,歡呼聲 – dreza

+0

可以得到任何國家的本地時間只是提供時區信息,以野田庫。如果是,那麼可以指向我正確的文章或示例代碼。謝謝 – Thomas

相關問題