简体   繁体   中英

C# Nullable DateTime Formatting Error - Cannot implicitly convert type 'string' to 'System.DateTime?'

I have a nullable datetime column in my database.

In my viewmodel I have this property defined as follows:

public DateTime? ExpiryDate { get; set; }

In my controller edit method I am trying to set the value of this property as follows:

 viewModel.ExpiryDate = topic.ExpiryDate.HasValue ?
          topic.ExpiryDate.Value.ToString("DD MMM YYYY") : null;

But I'm getting error:

 Cannot implicitly convert type 'string' to 'System.DateTime?'

If I have the following ie non nullable, it works fine without any errors:

 public DateTime ExpiryDate { get; set; }

 viewModel.ExpiryDate = topic.ExpiryDate.ToString("DD MMM YYYY")

do this:

viewModel.ExpiryDate = topic.ExpiryDate.HasValue ?
          topic.ExpiryDate.Value : null;

With this code .ToString("DD MMM YYYY") , you're passing a string to a DateTime type property. Please make sure viewModel.ExpiryDate is also a nullable DateTime type since you're trying to assign a null value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM