我有这些输入字符串:
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 Time 类型:
// 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”,它处理不明确或跳过的本地日期/时间值,如下所示:
ambiguous values map to the earlier of the alternatives, and "skipped" values are shifted forward by the duration of the "gap".
这可能就是您想要的。还有 InZoneStrictly
,如果给定的本地日期/时间没有表示一个时间点,它会抛出异常,或者你可以调用 InZone
并传入你的拥有 ZoneLocalMappingResolver
。
关于c# - 如何获取具有本地时间信息的 DateTimeOffset,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50580872/