C#⽇期格式的转换⽅法
C#中⼀些⽇期格式的转换。
创建公共⽅法类(UtilityHandle.cs),代表如下:
/// <summary>
/// 公共⽅法类
/// </summary>
public static class UtilityHandle
{
/// <summary>
///  字符串⽇期转DateTime
/// </summary>
public static DateTime TransStrToDateTime(string strDateTime)
{
DateTime now;
string[] format = new string[]
{
"yyyyMMddHHmmss", "yyyy-MM-dd HH:mm:ss", "yyyy年MM⽉dd⽇ HH时mm分ss秒",
"yyyyMdHHmmss","yyyy年M⽉d⽇ H时mm分ss秒", "yyyy.M.d H:mm:ss", "yyyy.MM.dd HH:mm:ss","yyyy-MM-dd","yyyyMMdd"            ,"yyyy/MM/dd","yyyy/M/d"
};
if (DateTime.TryParseExact(strDateTime, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out now))
{
return now;
}
return DateTime.MinValue;
}
/// <summary>
/// ⽇期转换
/// </summary>
public static string TransformDataLong(DateTime? dateTime)
{
string result = "";
if (dateTime.HasValue)
{
result = dateTime.Value.ToString("yyyy-MM-dd HH:mm:ss");
}
return result;
}
/// <summary>
/// ⽇期转换
/// </summary>
public static string TransformDataShort(DateTime? dateTime)
{
string result = "";
if (dateTime.HasValue)
{
result = dateTime.Value.ToString("yyyy-MM-dd");
}
return result;
}
/// <summary>
/// 将⽇期转换成decimal
/// </summary>
public static decimal TransDateTimeToDecimal(DateTime date)
{
decimal ret = 0;
ret = Convert.ToDecimal(date.ToString("yyyyMMddHHmmss"));
return ret;
string转date的方法
}
/// <summary>
/// 将decimal转换成⽇期格式
/// </summary>
/// <param name="date">yyyyMMddHHmmss</param>
/// <returns>yyyy-MM-dd HH:mm:ss</returns>
public static string TransDecimalToDateTime(string date)
{
DateTimeFormatInfo dtfi = new CultureInfo("zh-CN", false).DateTimeFormat;
DateTime dateTime = DateTime.Now;
DateTime.TryParseExact(date, "yyyyMMddHHmmss", dtfi, DateTimeStyles.None, out dateTime);        return dateTime.ToString("yyyy-MM-dd HH:mm:ss"); ;
}
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。