2

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 i.e non nullable, it works fine without any errors:

 public DateTime ExpiryDate { get; set; }

 viewModel.ExpiryDate = topic.ExpiryDate.ToString("DD MMM YYYY")
3
  • 1
    viewModel.ExpiryDate is a DateTime? but you're trying to assign a string. Isn't it clear? A DateTime has no format, what are you trying to achieve with ToString("DD MMM YYYY") here? Commented Jun 16, 2016 at 8:00
  • Clearly ExpiryDate should be assigned as Convert.ToDateTime(string format) or DateTime.ParseExact(string format). Commented Jun 16, 2016 at 8:01
  • ExpiryDate is a nullable DateTime value in my database table. In my view I want to format its display inside a textbox field. That is why i'm trying to format it when I assign it the the viewmodel. Commented Jun 16, 2016 at 8:21

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

4 Comments

why not directly viewModel.ExpiryDate = topic.ExpiryDate?
not sure what is the type of both but you're correct fubo. :)
Convert.ToDateTime(String.Format("{0:dd MMM yyyy}", topic.ExpiryDate.Value) or DateTime.ParseExact(topic.ExpiryDate.Value, "dd MMM yyyy", CultureInfo.InvariantCulture) are possible if OP requires certain date format, i.e. topic.ExpiryDate is a string and not DateTime.
@ Tetsuya topic.ExpiryDate is a datetime value which can be nullable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.