How can I format a nullable DateTime with ToString()?

前端 未结 20 2204
面向向阳花
面向向阳花 2020-11-27 12:04

How can I convert the nullable DateTime dt2 to a formatted string?

DateTime dt = DateTime.Now;
Console.WriteLine(dt.ToString(\"yyyy-MM-dd hh         


        
相关标签:
20条回答
  • 2020-11-27 12:41

    RAZOR syntax:

    @(myNullableDateTime?.ToString("yyyy-MM-dd") ?? String.Empty)
    
    0 讨论(0)
  • 2020-11-27 12:42

    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'
    
    0 讨论(0)
  • 2020-11-27 12:42

    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";
    }
    
    0 讨论(0)
  • 2020-11-27 12:43

    C# 6.0 baby:

    dt2?.ToString("dd/MM/yyyy");

    0 讨论(0)
  • 2020-11-27 12:43

    What about something as easy as this:

    String.Format("{0:dd/MM/yyyy}", d2)
    
    0 讨论(0)
  • 2020-11-27 12:45

    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

    0 讨论(0)
提交回复
热议问题