Nodatime根据时间和时区创建ZonedDateTime

Bri*_*ice 5 c# timezone nodatime

任何人都可以给我最直接的方式来创建ZonedDateTime,给定"下午4:30"和"America/Chicago".

我希望此对象表示该时区中当前日期的时间.

谢谢!

我尝试了这个......但它似乎实际上给了我一个本地时区的瞬间,它在创建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);
Run Code Online (Sandbox Code Playgroud)

Mat*_*int 8

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);
Run Code Online (Sandbox Code Playgroud)

几点说明:

  • 我故意将许多项分成单独的变量,以便您可以看到从一种类型到下一种类型的进展.您可以根据需要压缩它们以减少代码行数.我还使用了显式类型名称.随意使用var.

  • 你可能想把它放在一个函数中.执行此操作时,应将clock变量作为参数传入.这将允许您FakeClock在单元测试中替换a的系统时钟.

  • 一定要了解InZoneLeniently行为方式,并注意它在即将发布的2.0版本中的变化.请参阅2.x迁移指南 "Lenient解析器更改" .

  • 在2.0中,如果您要重复从同一时区获取当前日期/时间,您还可以使用`ZonedClock`来简化操作. (2认同)