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

时间:2018-05-29 09:27:54

标签: c# nodatime

我有这些输入字符串:

var timeStr = "03:22";
var dateStr = "2018/01/12";
var format = "yyyy/MM/dd";
var timeZone = "Asia/Tehran";

这是我所拥有的时间的信息,timeStr位于Asia/Tehran时区且不是UTC。

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

2 个答案:

答案 0 :(得分:7)

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

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

  

模棱两可的值映射到较早的替代品,&#34;跳过&#34;价值向前移动了#34;间隙&#34;。

这可能或可能是你想要的。还有InZoneStrictly如果没有给定的本地日期/时间表示的单个即时时间,则会抛出异常,或者您可以调用InZone并传入您自己的ZoneLocalMappingResolver

答案 1 :(得分:-1)

如果您正在寻找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