C# 泛型日期(DateTime?)扩展方法 DateTimeExtension
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
/// <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
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
版权声明:本文为开发框架文库发布内容,转载请附上原文出处连接
NewDoc C/S框架网