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

前端 未结 20 2206
面向向阳花
面向向阳花 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:47

    Here is a more generic approach. This will allow you to string format any nullable value type. I have included the second method to allow overriding the default string value instead of using the default value for the value type.

    public static class ExtensionMethods
    {
        public static string ToString<T>(this Nullable<T> nullable, string format) where T : struct
        {
            return String.Format("{0:" + format + "}", nullable.GetValueOrDefault());
        }
    
        public static string ToString<T>(this Nullable<T> nullable, string format, string defaultValue) where T : struct
        {
            if (nullable.HasValue) {
                return String.Format("{0:" + format + "}", nullable.Value);
            }
    
            return defaultValue;
        }
    }
    
    0 讨论(0)
  • 2020-11-27 12:47

    I like this option:

    Console.WriteLine(dt2?.ToString("yyyy-MM-dd hh:mm:ss") ?? "n/a");
    
    0 讨论(0)
提交回复
热议问题