Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert UTC time to local time using Nodatime

Tags:

c#

nodatime

I have been provided a time in this format "ddMMyyHHmmss". I know the time is in UTC format. I would like to use the NodaTime library to convert this to my local timezone but I can't seem to figure it out. My local timezone target is to be New Zealand.

Here's what I have tried:

 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);
like image 842
dreza Avatar asked Jul 16 '13 02:07

dreza


People also ask

How do you convert UTC time to local time in HTML?

Use the Date() constructor to convert UTC to local time, e.g. new Date(utcDateStr) . Passing a date and time string in ISO 8601 format to the Date() constructor converts the UTC date and time to local time. Copied!

How do I convert DateTime to local time?

The ToLocalTime method converts a DateTime value from UTC to local time. To convert the time in any designated time zone to local time, use the TimeZoneInfo. ConvertTime method. The value returned by the conversion is a DateTime whose Kind property always returns Local.

How do you convert string to UTC time?

Using DateTimeOffset. Parse(string) or DateTimeOffset. ParseExact(string) with the . UtcDateTime converter correctly changed the kind of the DateTime to UTC, but also converted the time.


1 Answers

// 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
like image 93
Matt Johnson-Pint Avatar answered Oct 02 '22 21:10

Matt Johnson-Pint