How can I convert the nullable DateTime dt2 to a formatted string?
DateTime dt = DateTime.Now;
Console.WriteLine(dt.ToString(\"yyyy-MM-dd hh
RAZOR syntax:
@(myNullableDateTime?.ToString("yyyy-MM-dd") ?? String.Empty)
As others have stated you need to check for null before invoking ToString but to avoid repeating yourself you could create an extension method that does that, something like:
public static class DateTimeExtensions {
public static string ToStringOrDefault(this DateTime? source, string format, string defaultValue) {
if (source != null) {
return source.Value.ToString(format);
}
else {
return String.IsNullOrEmpty(defaultValue) ? String.Empty : defaultValue;
}
}
public static string ToStringOrDefault(this DateTime? source, string format) {
return ToStringOrDefault(source, format, null);
}
}
Which can be invoked like:
DateTime? dt = DateTime.Now;
dt.ToStringOrDefault("yyyy-MM-dd hh:mm:ss");
dt.ToStringOrDefault("yyyy-MM-dd hh:mm:ss", "n/a");
dt = null;
dt.ToStringOrDefault("yyyy-MM-dd hh:mm:ss", "n/a") //outputs 'n/a'
Here is Blake's excellent answer as an extension method. Add this to your project and the calls in the question will work as expected.
Meaning it is used like MyNullableDateTime.ToString("dd/MM/yyyy")
, with the same output as MyDateTime.ToString("dd/MM/yyyy")
, except that the value will be "N/A"
if the DateTime is null.
public static string ToString(this DateTime? date, string format)
{
return date != null ? date.Value.ToString(format) : "N/A";
}
C# 6.0 baby:
dt2?.ToString("dd/MM/yyyy");
What about something as easy as this:
String.Format("{0:dd/MM/yyyy}", d2)
Maybe it is a late answer but may help anyone else.
Simple is:
nullabledatevariable.Value.Date.ToString("d")
or just use any format rather than "d".
Best