Nodatime creates ZonedDateTime based on time and timezone

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

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

Thanks!

I tried this ... but it seems to actually give me an instant in the local time zone, which gets the 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);
+4
source share
1 answer
using NodaTime;
using NodaTime.Text;

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

// parse the time string using Noda Time 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:

  • , . . . var.

  • . , clock . FakeClock .

  • , InZoneLeniently, , 2.0. . " Lenient" 2.x.

+7

Source: https://habr.com/ru/post/1622149/


All Articles