Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

datetime

xaml

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.

like image 937
S.B.Wrede Avatar asked Dec 11 '15 12:12

S.B.Wrede


People also ask

How do I convert DateTimeOffset to local time?

In performing the conversion to local time, the method first converts the current DateTimeOffset object's date and time to Coordinated Universal Time (UTC) by subtracting the offset from the time. It then converts the UTC date and time to local time by adding the local time zone offset.

What is the difference between DateTime and DateTimeOffset?

Perhaps the most obvious difference is that the datetimeoffset stores the time zone offset, whereas datetime doesn't. Another important difference is that datetimeoffset allows you to specify the precision (up to 7 decimal places).

Is DateTimeOffset UTC?

Now Property (System) Gets a DateTimeOffset object that is set to the current date and time on the current computer, with the offset set to the local time's offset from Coordinated Universal Time (UTC).

Is DateTimeOffset better than DateTime?

The DateTimeOffset structure provides more time zone awareness than the DateTime structure.


1 Answers

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;
like image 177
David Pine Avatar answered Nov 16 '22 00:11

David Pine