简体   繁体   中英

How do I convert a DateTimeOffset? to DateTime in C#?

I need to convert a DateTimeOffset? to a DateTime. The value originally comes from a XAML CalendarDatePicker, but I need to change it to DateTime to store the value. I have found this description of how to convert DateTimeOffset, but I do not think that it answers my question because they don't use a nullable type.

Nullable types are useful, but can sometimes be confusing at first. The Nullable<T> is a struct where T is a struct as well. This struct wraps the value for the instance variable T and exposes three primary members.

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).

You can make any struct nullable by adding a ' ? ' after the declaration of the variable type, or by wrapping the variable type with Nullable< varible type here > . As depicted below:

Nullable<DateTimeOffset> a = null;
DateTimeOffset? b = null;

I believe that what you would want here is to check if there is in fact a value with .HasValue and then take the .Value from the offset and perform your standard conversion.

Example

var now = DateTime.Now;
DateTimeOffset? offset = now;
DateTime dateTime = offset.HasValue ? offset.Value.DateTime : DateTime.MaxValue;

Or if you want a DateTime? do this:

var now = DateTime.Now;
DateTimeOffset? offset = now;
DateTime? dateTime = offset.HasValue ? offset.Value.DateTime : (DateTime?)null;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM