I want to convert a nullable DateTime (DateTime?
) to a DateTime
, but I am getting an error:
Cannot implicitly convert type
Try this
DateTime UpdatedTime = _objHotelPackageOrder.UpdatedDate ?? DateTime.Now;
How about the following:
DateTime UpdatedTime = _objHotelPackageOrder.UpdatedDate.HasValue ? _objHotelPackageOrder.UpdatedDate.value : DateTime.Now;
MS already made a method for this, so you dont have to use the null coalescing operator. No difference in functionality, but it is easier for non-experts to get what is happening at a glance.
DateTime updatedTime = _objHotelPackageOrder.UpdatedDate.GetValueOrDefault(DateTime.Now);
You can also try Nullable(T) Properties:
DateTime UpdatedTime = _objHotelPackageOrder.UpdatedDate.HasValue
? DateTime.Now : _objHotelPackageOrder.UpdatedDate.Value;
Here is a snippet I used within a Presenter filling a view with a Nullable Date/Time
memDateLogin = m.memDateLogin ?? DateTime.MinValue