Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get short date for System Nullable datetime (datetime ?) in C#

How to get short date for Get short date for System Nullable datetime (datetime ?)

for ed 12/31/2013 12:00:00 --> only should return 12/31/2013.

I don't see the ToShortDateString available.

like image 980
user2811143 Avatar asked Sep 24 '13 12:09

user2811143


People also ask

How do you make a date time Nullable?

The Nullable < T > structure is using a value type as a nullable type. By default DateTime is not nullable because it is a Value Type, using the nullable operator introduced in C# 2, you can achieve this. Using a question mark (?) after the type or using the generic style Nullable.

How can I get only the date from DateTime format?

ToString() − One more way to get the date from DateTime is using ToString() extension method. The advantage of using ToString() extension method is that we can specify the format of the date that we want to fetch. DateTime. Date − will also remove the time from the DateTime and provides us the Date only.

Can DateTime be nullable?

DateTime CAN be compared to null; It cannot hold null value, thus the comparison will always be false. DateTime is a "Value Type". Basically a "value type" can't set to NULL. But by making them to "Nullable" type, We can set to null.

What is the default value of Nullable DateTime in C#?

To clarify the answer's "finally" a bit - the default of Nullable<DateTime> (DateTime?) is null, because Nullable<T> creates a reference type.


2 Answers

You need to use .Value first (Since it's nullable).

var shortString = yourDate.Value.ToShortDateString(); 

But also check that yourDate has a value:

if (yourDate.HasValue) {    var shortString = yourDate.Value.ToShortDateString(); } 
like image 70
Darren Avatar answered Sep 28 '22 20:09

Darren


string.Format("{0:d}", dt); works:

DateTime? dt = (DateTime?)DateTime.Now; string dateToday = string.Format("{0:d}", dt); 

Demo

If the DateTime? is null this returns an empty string.

Note that the "d" custom format specifier is identical to ToShortDateString.

like image 29
Tim Schmelter Avatar answered Sep 28 '22 20:09

Tim Schmelter