2013-07-16 21 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

関連する問題