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.
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.
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).
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).
The DateTimeOffset structure provides more time zone awareness than the DateTime structure.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With