Summary: in this tutorial, you will learn how to convert a datetime to a DATE by using the CONVERT() , TRY_CONVERT() , and CAST() functions. To convert a datetime to a date, you can use the CONVERT() , TRY_CONVERT() , or CAST() function.
You can't change a DateTime value - it's immutable. However, you can change the variable to have a new value. The easiest way of doing that to change just the time is to create a TimeSpan with the relevant time, and use the DateTime.
You want to use the null-coalescing operator, which is designed for exactly this purpose.
Using it you end up with this code.
DateTime UpdatedTime = _objHotelPackageOrder.UpdatedDate ?? 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);
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;
How about the following:
DateTime UpdatedTime = _objHotelPackageOrder.UpdatedDate.HasValue ? _objHotelPackageOrder.UpdatedDate.value : DateTime.Now;
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