Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nodatime create a ZonedDateTime given a time and timezone

Can anyone give me the most straightforward way to create a ZonedDateTime, given "4:30pm" and "America/Chicago".

I want this object to represent that time for the current date in that timezone.

Thanks!

I tried this... but it seems to actually give me an instant in the local timezone which gets offset when creating the zonedDateTime.

        string time = "4:30pm";
        string timezone = "America/Chicago";
        DateTime dateTime;
        if (DateTime.TryParse(time, out dateTime))
        {
            var instant = new Instant(dateTime.Ticks);
            DateTimeZone tz = DateTimeZoneProviders.Tzdb[timezone];
            var zonedDateTime = instant.InZone(tz);
like image 201
Brian Rice Avatar asked Dec 29 '15 23:12

Brian Rice


1 Answers

using NodaTime;
using NodaTime.Text;

// your inputs
string time = "4:30pm";
string timezone = "America/Chicago";

// parse the time string using Noda Time's pattern API
LocalTimePattern pattern = LocalTimePattern.CreateWithCurrentCulture("h:mmtt");
ParseResult<LocalTime> parseResult = pattern.Parse(time);
if (!parseResult.Success) {
    // handle parse failure
}
LocalTime localTime = parseResult.Value;

// get the current date in the target time zone
DateTimeZone tz = DateTimeZoneProviders.Tzdb[timezone];
IClock clock = SystemClock.Instance;
Instant now = clock.Now;
LocalDate today = now.InZone(tz).Date;

// combine the date and time
LocalDateTime ldt = today.At(localTime);

// bind it to the time zone
ZonedDateTime result = ldt.InZoneLeniently(tz);

A few notes:

  • I intentionally separated many items into separate variables so you could see the progression from one type to the next. You may condense them as desired for fewer lines of code. I also used the explicit type names. Feel free to use var.

  • You may want to put this in a function. When you do, you should pass in the clock variable as a parameter. This will let you replace the system clock for a FakeClock in your unit tests.

  • Be sure to understand how InZoneLeniently behaves, and note how it's changing in the upcoming 2.0 release. See "Lenient resolver changes" in the 2.x migration guide.

like image 60
Matt Johnson-Pint Avatar answered Oct 14 '22 23:10

Matt Johnson-Pint