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

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

    Simple generic extensions

    public static class Extensions
    {
    
        /// 
        /// Generic method for format nullable values
        /// 
        /// Formated value or defaultValue
        public static string ToString(this Nullable nullable, string format, string defaultValue = null) where T : struct
        {
            if (nullable.HasValue)
            {
                return String.Format("{0:" + format + "}", nullable.Value);
            }
    
            return defaultValue;
        }
    }
    

提交回复
热议问题