如何转换DateTimeOffset?到C#中的DateTime?

S.B*_*ede 2 c# xaml datetime

我需要转换DateTimeOffset吗?到DateTime。该值最初来自XAML CalendarDatePicker,但我需要将其更改为DateTime来存储值。我已经找到了有关如何转换DateTimeOffset的描述,但我认为它不能回答我的问题,因为它们不使用可为空的类型。

Dav*_*ine 5

可为空的类型很有用,但一开始有时会造成混淆。的Nullable<T>是一个结构,其中T是一个结构为好。该结构包装实例变量T的值,并公开三个主要成员。

HasValue // Returns bool indicating whether there is a value present.

Value // Returns the value of T if one is present, or throws.

GetValueOrDefault() // Gets the value or returns default(T).
Run Code Online (Sandbox Code Playgroud)

您可以通过?在变量类型的声明后添加' '或Nullable<在此处将变量类型包装为可变类型来使任何结构可为空>。如下图所示:

Nullable<DateTimeOffset> a = null;
DateTimeOffset? b = null;
Run Code Online (Sandbox Code Playgroud)

我相信您要在此处检查的是是否确实存在一个值,.HasValue然后.Value从偏移量中提取并执行标准转换。

例

var now = DateTime.Now;
DateTimeOffset? offset = now;
DateTime dateTime = offset.HasValue ? offset.Value.DateTime : DateTime.MaxValue;
Run Code Online (Sandbox Code Playgroud)

或者,如果您想DateTime?要这样做:

var now = DateTime.Now;
DateTimeOffset? offset = now;
DateTime? dateTime = offset.HasValue ? offset.Value.DateTime : (DateTime?)null;
Run Code Online (Sandbox Code Playgroud)

  • 但实际上我如何从 DateTimeOffset 进行转换?到日期时间?? (3认同)
  • 不知道为什么这不被接受为答案。像魅力一样工作。 (2认同)