How to convert DateTime? to DateTime

前端 未结 11 2004
醉话见心
醉话见心 2020-12-07 15:17

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

Cannot implicitly convert type

相关标签:
11条回答
  • 2020-12-07 15:40
    DateTime UpdatedTime = _objHotelPackageOrder.HasValue ? _objHotelPackageOrder.UpdatedDate.Value : DateTime.Now;
    
    0 讨论(0)
  • 2020-12-07 15:42

    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;
    
    0 讨论(0)
  • 2020-12-07 15:42

    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;
    
    0 讨论(0)
  • 2020-12-07 15:44

    You can use a simple cast:

    DateTime dtValue = (DateTime) dtNullAbleSource;
    

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

    0 讨论(0)
  • 2020-12-07 15:45

    Consider using the following which its far better than the accepted answer

    DateTime UpdatedTime = _objHotelPackageOrder.UpdatedDate == null 
        ? DateTime.Now : (DateTime)_objHotelPackageOrder.UpdatedDate;
    
    0 讨论(0)
  • 2020-12-07 15:46

    Try this:

    DateTime UpdatedTime = (DateTime)_objHotelPackageOrder.UpdatedDate == null ? DateTime.Now : _objHotelPackageOrder.UpdatedDate.Value;
    
    0 讨论(0)
提交回复
热议问题