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

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

    You can use dt2.Value.ToString("format"), but of course that requires that dt2 != null, and that negates th use of a nullable type in the first place.

    There are several solutions here, but the big question is: How do you want to format a null date?

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

    I think you have to use the GetValueOrDefault-Methode. The behaviour with ToString("yy...") is not defined if the instance is null.

    dt2.GetValueOrDefault().ToString("yyy...");
    
    0 讨论(0)
  • 2020-11-27 12:36

    Even a better solution in C# 6.0:

    DateTime? birthdate;
    
    birthdate?.ToString("dd/MM/yyyy");
    
    0 讨论(0)
  • 2020-11-27 12:36

    IFormattable also includes a format provider that can be used, it allows both format of IFormatProvider to be null in dotnet 4.0 this would be

    /// <summary>
    /// Extentionclass for a nullable structs
    /// </summary>
    public static class NullableStructExtensions {
    
        /// <summary>
        /// Formats a nullable struct
        /// </summary>
        /// <param name="source"></param>
        /// <param name="format">The format string 
        /// If <c>null</c> use the default format defined for the type of the IFormattable implementation.</param>
        /// <param name="provider">The format provider 
        /// If <c>null</c> the default provider is used</param>
        /// <param name="defaultValue">The string to show when the source is <c>null</c>. 
        /// If <c>null</c> an empty string is returned</param>
        /// <returns>The formatted string or the default value if the source is <c>null</c></returns>
        public static string ToString<T>(this T? source, string format = null, 
                                         IFormatProvider provider = null, 
                                         string defaultValue = null) 
                                         where T : struct, IFormattable {
            return source.HasValue
                       ? source.Value.ToString(format, provider)
                       : (String.IsNullOrEmpty(defaultValue) ? String.Empty : defaultValue);
        }
    }
    

    using together with named parameters you can do:

    dt2.ToString(defaultValue: "n/a");

    In older versions of dotnet you get a lot of overloads

    /// <summary>
    /// Extentionclass for a nullable structs
    /// </summary>
    public static class NullableStructExtensions {
    
        /// <summary>
        /// Formats a nullable struct
        /// </summary>
        /// <param name="source"></param>
        /// <param name="format">The format string 
        /// If <c>null</c> use the default format defined for the type of the IFormattable implementation.</param>
        /// <param name="provider">The format provider 
        /// If <c>null</c> the default provider is used</param>
        /// <param name="defaultValue">The string to show when the source is <c>null</c>. 
        /// If <c>null</c> an empty string is returned</param>
        /// <returns>The formatted string or the default value if the source is <c>null</c></returns>
        public static string ToString<T>(this T? source, string format, 
                                         IFormatProvider provider, string defaultValue) 
                                         where T : struct, IFormattable {
            return source.HasValue
                       ? source.Value.ToString(format, provider)
                       : (String.IsNullOrEmpty(defaultValue) ? String.Empty : defaultValue);
        }
    
        /// <summary>
        /// Formats a nullable struct
        /// </summary>
        /// <param name="source"></param>
        /// <param name="format">The format string 
        /// If <c>null</c> use the default format defined for the type of the IFormattable implementation.</param>
        /// <param name="defaultValue">The string to show when the source is null. If <c>null</c> an empty string is returned</param>
        /// <returns>The formatted string or the default value if the source is <c>null</c></returns>
        public static string ToString<T>(this T? source, string format, string defaultValue) 
                                         where T : struct, IFormattable {
            return ToString(source, format, null, defaultValue);
        }
    
        /// <summary>
        /// Formats a nullable struct
        /// </summary>
        /// <param name="source"></param>
        /// <param name="format">The format string 
        /// If <c>null</c> use the default format defined for the type of the IFormattable implementation.</param>
        /// <param name="provider">The format provider (if <c>null</c> the default provider is used)</param>
        /// <returns>The formatted string or an empty string if the source is <c>null</c></returns>
        public static string ToString<T>(this T? source, string format, IFormatProvider provider)
                                         where T : struct, IFormattable {
            return ToString(source, format, provider, null);
        }
    
        /// <summary>
        /// Formats a nullable struct or returns an empty string
        /// </summary>
        /// <param name="source"></param>
        /// <param name="format">The format string 
        /// If <c>null</c> use the default format defined for the type of the IFormattable implementation.</param>
        /// <returns>The formatted string or an empty string if the source is null</returns>
        public static string ToString<T>(this T? source, string format)
                                         where T : struct, IFormattable {
            return ToString(source, format, null, null);
        }
    
        /// <summary>
        /// Formats a nullable struct
        /// </summary>
        /// <param name="source"></param>
        /// <param name="provider">The format provider (if <c>null</c> the default provider is used)</param>
        /// <param name="defaultValue">The string to show when the source is <c>null</c>. If <c>null</c> an empty string is returned</param>
        /// <returns>The formatted string or the default value if the source is <c>null</c></returns>
        public static string ToString<T>(this T? source, IFormatProvider provider, string defaultValue)
                                         where T : struct, IFormattable {
            return ToString(source, null, provider, defaultValue);
        }
    
        /// <summary>
        /// Formats a nullable struct or returns an empty string
        /// </summary>
        /// <param name="source"></param>
        /// <param name="provider">The format provider (if <c>null</c> the default provider is used)</param>
        /// <returns>The formatted string or an empty string if the source is <c>null</c></returns>
        public static string ToString<T>(this T? source, IFormatProvider provider)
                                         where T : struct, IFormattable {
            return ToString(source, null, provider, null);
        }
    
        /// <summary>
        /// Formats a nullable struct or returns an empty string
        /// </summary>
        /// <param name="source"></param>
        /// <returns>The formatted string or an empty string if the source is <c>null</c></returns>
        public static string ToString<T>(this T? source) 
                                         where T : struct, IFormattable {
            return ToString(source, null, null, null);
        }
    }
    
    0 讨论(0)
  • 2020-11-27 12:38

    The problem with formulating an answer to this question is that you do not specify the desired output when the nullable datetime has no value. The following code will output DateTime.MinValue in such a case, and unlike the currently accepted answer, will not throw an exception.

    dt2.GetValueOrDefault().ToString(format);
    
    0 讨论(0)
  • 2020-11-27 12:39

    Simple generic extensions

    public static class Extensions
    {
    
        /// <summary>
        /// Generic method for format nullable values
        /// </summary>
        /// <returns>Formated value or defaultValue</returns>
        public static string ToString<T>(this Nullable<T> nullable, string format, string defaultValue = null) where T : struct
        {
            if (nullable.HasValue)
            {
                return String.Format("{0:" + format + "}", nullable.Value);
            }
    
            return defaultValue;
        }
    }
    
    0 讨论(0)
提交回复
热议问题