Tuesday, January 14, 2014

Formatting Nullable DateTime to short date.

When it was a datetime variable, which needs formatting to a short date string, it was simple. But recently I had to face a situation where I need to deal with nullable datetime and format it to short date string. Though it was simple, but not as straightforward as it is for a regular datetime variable.

  Lets see some examples on both to diagnose the approach to return values in short date string format.

When we try to format a date time variable to short date string, it looks like

DateTime newDate = DateTime.Now;

To set it to have a display format, then you could write it as,

newDate.ToShortDateString("MM/dd/yyyy");

But if we try to do the same with DateTime?, it will throw an exception. To avoid this, we need to read the Value from DateTime? and convert that to a short date string format.

Here is an example below:

 DateTime? newDate = null;
string finalDate = string.Empty;
finalDate = newDate.HasValue ? newDate.Value.ToShortDateString() :                      DateTime.Now.ToShortDateString();

1 comment: