Nodatime 在给定时间和时区的情况下创建 ZonedDateTime
Nodatime create a ZonedDateTime given a time and timezone
谁能给我最直接的方法来创建 ZonedDateTime,给定“4:30pm”和 "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);
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);
一些注意事项:
我故意将许多项目分成单独的变量,这样您就可以看到从一种类型到另一种类型的进展。您可以根据需要压缩它们以获得更少的代码行。我还使用了显式类型名称。随意使用 var
.
你可能想把它放在一个函数中。当你这样做时,你应该传入 clock
变量作为参数。这将允许您在单元测试中将系统时钟替换为 FakeClock
。
一定要了解 InZoneLeniently
的行为方式,并注意它在即将发布的 2.0 版本中的变化。参见 the 2.x migration guide 中的 "Lenient resolver changes"。
谁能给我最直接的方法来创建 ZonedDateTime,给定“4:30pm”和 "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);
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);
一些注意事项:
我故意将许多项目分成单独的变量,这样您就可以看到从一种类型到另一种类型的进展。您可以根据需要压缩它们以获得更少的代码行。我还使用了显式类型名称。随意使用
var
.你可能想把它放在一个函数中。当你这样做时,你应该传入
clock
变量作为参数。这将允许您在单元测试中将系统时钟替换为FakeClock
。一定要了解
InZoneLeniently
的行为方式,并注意它在即将发布的 2.0 版本中的变化。参见 the 2.x migration guide 中的 "Lenient resolver changes"。