I don't know if this makes sense but I have a DateTime? object and I only want the date portion of it, but I need it to convert it back to a DateTime? and store it with only Date value. Is this possible?
This is what I tried:
public DateTime? StartDate{ get; set; };
DateTime? x = Convert.ToDateTime(StartDate.Value.ToString("MM-dd-yyyy"));
If I just keep
StartDate.Value.ToString("MM-dd-yyyy")
it works but I still want a DateTime? object because that is how my database is storing it. How can I achieve this?
You can do this:
DateTime? x = StartDate.HasValue //Handle when value is null
? StartDate.Value.Date //If not null, get date part
: (DateTime?)null; //otherwise just return null
A simpler version uing the null-conditional operator would be:
DateTime? x = StartDate2?.Date;
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