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

标签 c# nodatime

我有这些输入字符串:

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

这是我所拥有的时间信息,timeStrAsia/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/

相关文章:

c# - 将一周中的几天列表分组为连续几天的组

c# - 用于从集合中删除对象的迭代器的 Java 模拟

c# - 如何编写一个可能返回两种不同类型的方法?

c# word-2007 加载项 : get the path and filename of current opened wordfile?

c# - .NET NodaTime 如何创建自定义时区?

c# - 输出一个 ISO 8601 字符串

c# - 如何获取具有给定属性的属性列表?

c# - 检查 List<List<double>> 在第一个位置是否包含特定值

c# - 使用 Noda Time,如何使用 LocalDate 和 LocalTime 创建 LocalDateTime

date - 野田市时间日期比较