Link to home
Start Free TrialLog in
Avatar of jwebster77
jwebster77

asked on

Convert to datetime in yyyy-mm-dd format

Hello,
In C#, I would like to convert whatever will be in "assignedDateTest" (either a date or null) in the below code to datetime format.  Format should be yyyy-mm-dd without the time.  How could I do that?  Thank you.

var assignedDateTest = (dr["dtAssignedDate"]) is DBNull ? (DateTime?)null : (DateTime?)dr["dtAssignedDate"];

Open in new window

Avatar of gr8gonzo
gr8gonzo
Flag of United States of America image

if(assignedDateTest != null)
{
  string output = ((DateTime)assignedDateTest).ToString("yyyy-MM-dd");
}

Open in new window

Avatar of jwebster77
jwebster77

ASKER

I would get an error with the code you suggested because that value must remain a datetime datatype as that is what that field is in the model(same model used in other places as well).

This is the model:
public Nullable<System.DateTime> dtAssignedDate { get; set; }

Open in new window

This is the part of the code that will store that value in the model field(FYI, this line of code is in a SqlDataReader):
dtAssignedDate = assignedDateTest,

Open in new window


I'm not sure I understand what you're saying. The DateTime value holds a raw date and time value. It is not stored in a specific format like YYYY-MM-DD.

If you want to display the value of a DateTime object in YYYY-MM-DD, then you use ToString() to create a representation of that value in the specified format.

Typically you keep the DateTime value in memory and then you simply use the ToString() method at the point at which you want to display or output it in a specific format. Or, if you output it in a control like a DataGrid column, you would simply indicate the formatting in the control's layout properties.

The code I was providing was the more "raw" approach to formatting a DateTime value into a specific YYYY-MM-DD string output.
A DateTime, as its name implies, always have a time portion.

If you simply want to remove the time portion, use ((DateTime?)dr["dtAssignedDate"] ).Date

This will keep the date and assign a time portion set to 00:00:00. This has been the way to deal only with dates since COM in the middle of the 90's. This is what happens when you do something such as d = Date.Today. It stores 00:00:00 in the time portion.

When you deal only with DateTime variables that are set to midnight, the time portion has no impact on your operations.

Simply use the ToString specified by gr8gonzo when you want to display it.
This question needs an answer!
Become an EE member today
7 DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform.
View membership options
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.