C# 泛型日期(DateTime?)扩展方法 DateTimeExtension
作者:C/S框架网|www.cscode.ne  发布日期:2021-05-30 15:46:48
  C# 泛型日期(DateTime?)扩展方法 DateTimeExtension


因DateTime?泛型日期没有ToString(format)的方法,写了个类给大家参考:

C# Code:


/// <summary>
/// 泛型日期扩展方法
/// </summary>
public static class DateTimeExtension
{
  
/// <summary>
  
/// 格式化日期字符串
  
/// </summary>
  
/// <param name="obj"></param>
  
/// <param name="format"></param>
  
/// <returns></returns>
  
public static string ToString(this DateTime? obj, string format)
  {
    
if (obj == null) return "";
    
return ((DateTime)obj).ToString(format);
  }
  
  
/// <summary>
  
/// 转换为DateTime
  
/// </summary>
  
/// <param name="obj"></param>
  
/// <returns></returns>
  
public static DateTime ToDateTime(this DateTime? obj)
  {
    
if (obj == null) return DateTime.MinValue;
    
return (DateTime)obj;
  }
  
  
/// <summary>
  
/// 格式化日期字符串
  
/// </summary>
  
/// <param name="obj"></param>
  
/// <param name="format"></param>
  
/// <returns></returns>
  
public static string ToStringEx(this DateTime obj, string format)
  {
    
if (obj == null) return "";
    
if (obj < DateTime.MinValue) return "";
    
return ((DateTime)obj).ToString(format);
  }
  
}

//来源:C/S框架网 | www.csframework.com | QQ:23404761




测试:


C# Code:

DateTime? d = DateTime.Now;
var dd = d.ToDateTime();
var ss = d.ToString("yyyyMMdd");
DateTime yy
= DateTime.Now;
var sy = yy.ToStringEx("yyyyMMdd");

//来源:C/S框架网 | www.csframework.com | QQ:23404761




上一篇 下一篇