如何获取具有本地时间信息的DateTimeOffset

meh*_*dvd 2 c# nodatime

我有这些输入字符串:

var timeStr = "03:22";
var dateStr = "2018/01/12";
var format = "yyyy/MM/dd";
var timeZone = "Asia/Tehran";
Run Code Online (Sandbox Code Playgroud)

这是我所拥有的时间的信息,timeStr它在Asia/Tehran时区中并且不在UTC中.

使用NodaTime,我如何获得一个DateTimeOffset对象,其中包含正确的偏移信息?

Jon*_*eet 7

让我们将您的所有信息转换为适当的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();
Run Code Online (Sandbox Code Playgroud)

注意"InZoneLeniently"处理模糊或跳过的本地日期/时间值,如下所示:

模糊值映射到备选项中较早的值,"跳过"值向前移动"间隙"的持续时间.

这可能或可能是你想要的.还有InZoneStrictly,这将抛出一个异常,如果不存在由给定的本地日期/时间表示的时间一个瞬间,或者您也可以拨打InZone,并通过在自己ZoneLocalMappingResolver.