Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert DateTime? to Date only and then back to DateTime? (Possible?)

Tags:

c#

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?

like image 236
testuser1231234 Avatar asked Sep 02 '25 06:09

testuser1231234


1 Answers

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;
like image 101
DavidG Avatar answered Sep 05 '25 17:09

DavidG