我有这些输入字符串:
var timeStr = "03:22";
var dateStr = "2018/01/12";
var format = "yyyy/MM/dd";
var timeZone = "Asia/Tehran";
这是我拥有的时间信息,timeStr
在Asia/Tehran
时区而不是UTC时区。
使用 NodaTime,我怎样才能获得一个包含正确偏移量的信息的 DateTimeOffset 对象?
让我们将所有信息转换为适当的 Noda 时间类型:
// Input values (as per the question)
var timeStr = "03:22";
var dateStr = "2018/01/12";
var format = "yyyy/MM/dd";
var timeZone = "Asia/Tehran";
// The patterns we'll use to parse input values
LocalTimePattern timePattern = LocalTimePattern.CreateWithInvariantCulture("HH:mm");
LocalDatePattern datePattern = LocalDatePattern.CreateWithInvariantCulture(format);
// The local parts, parsed with the patterns and then combined.
// Note that this will throw an exception if the values can't be parsed -
// use the ParseResult<T> return from Parse to check for success before
// using Value if you want to avoid throwing.
LocalTime localTime = timePattern.Parse(timeStr).Value;
LocalDate localDate = datePattern.Parse(dateStr).Value;
LocalDateTime localDateTime = localDate + localTime;
// Now get the time zone by ID
DateTimeZone zone = DateTimeZoneProviders.Tzdb[timeZone];
// Work out the zoned date/time being represented by the local date/time. See below for the "leniently" part.
ZonedDateTime zonedDateTime = localDateTime.InZoneLeniently(zone);
// The Noda Time type you want would be OffsetDateTime
OffsetDateTime offsetDateTime = zonedDateTime.ToOffsetDateTime();
// If you really want the BCL type...
DateTimeOffset dateTimeOffset = zonedDateTime.ToDateTimeOffset();
请注意"InZoneLeniently",它处理不明确或跳过的本地日期/时间值,如下所示:
不明确的值映射到较早的备选方案,"跳过"的值按"间隙"的持续时间向前移动。
这可能是你想要的,也可能是你想要的。还有InZoneStrictly
,如果给定的本地日期/时间没有表示一个时刻,或者您可以调用InZone
并传入您自己的ZoneLocalMappingResolver
,则会引发异常。
如果你正在寻找nodatime DateTimeOffset对象,你可以这样做:
var timeStr = "03:22";
var dateStr = "2018/01/12";
// DateTime.Parse can deal with this format without specs
// var format = "yyyy/MM/dd";
var timeZone = "Asia/Tehran";
var date = DateTime.Parse(timeStr + " " + dateStr);
var zone = DateTimeZoneProviders.Tzdb[timeZone];
var timespanOffset = zone.GetUtcOffset(SystemClock.Instance.Now).ToTimeSpan();
var result = new DateTimeOffset(date, timespanOffset);
Console.Write(result.ToUniversalTime());
其结果是 :1/11/2018 10:52:00 PM +00:00
对应于德黑兰时间 GMT +4,5