value - nullable datetime property in c#




How to convert DateTime? to DateTime (8)

I want to convert a nullable DateTime (DateTime?) to a DateTime, but I am getting an error:

Cannot implicitly convert type 'System.DateTime?' to 'System.DateTime'. An explicit conversion exists (are you missing a cast?)

I have attempted the following:

DateTime UpdatedTime = (DateTime)_objHotelPackageOrder.UpdatedDate == null 
    ? DateTime.Now : _objHotelPackageOrder.UpdatedDate;

Here is a snippet I used within a Presenter filling a view with a Nullable Date/Time

memDateLogin = m.memDateLogin ?? DateTime.MinValue

How about the following:

DateTime UpdatedTime = _objHotelPackageOrder.UpdatedDate.HasValue ? _objHotelPackageOrder.UpdatedDate.value : DateTime.Now;

Try this:

DateTime UpdatedTime = (DateTime)_objHotelPackageOrder.UpdatedDate == null ? DateTime.Now : _objHotelPackageOrder.UpdatedDate.Value;

Try this

DateTime UpdatedTime = _objHotelPackageOrder.UpdatedDate ?? DateTime.Now;

You can use a simple cast:

DateTime dtValue = (DateTime) dtNullAbleSource;

As Leandro Tupone said, you have to check if the var is null before


You need to call the Value property of the nullable DateTime. This will return a DateTime.

Assuming that UpdatedDate is DateTime?, then this should work:

DateTime UpdatedTime = (DateTime)_objHotelPackageOrder.UpdatedDate == null ? DateTime.Now : _objHotelPackageOrder.UpdatedDate.Value;

To make the code a bit easier to read, you could use the HasValue property instead of the null check:

DateTime UpdatedTime = _objHotelPackageOrder.UpdatedDate.HasValue
                          ? _objHotelPackageOrder.UpdatedDate.Value
                          : DateTime.Now;

This can be then made even more concise:

DateTime UpdatedTime = _objHotelPackageOrder.UpdatedDate ?? DateTime.Now;

rather user the following its far better

DateTime UpdatedTime = _objHotelPackageOrder.UpdatedDate == null 
    ? DateTime.Now : (DateTime)_objHotelPackageOrder.UpdatedDate;

DateTime UpdatedTime = _objHotelPackageOrder.HasValue ? _objHotelPackageOrder.UpdatedDate.Value : DateTime.Now;




datetime