本文实例讲述了C#实现日期格式转换的公共方法类。分享给大家供大家参考,具体如下:
这里演示了C#中一些日期格式的转换。
创建公共方法类(UtilityHandle.cs),代码如下:
代码如下 | 复制代码 |
/// /// 公共方法类 /// publicstaticclassUtilityHandle { /// /// 字符串日期转DateTime /// publicstaticDateTime TransStrToDateTime(stringstrDateTime) { DateTime now; string[] format =newstring[] { "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,outnow)) { returnnow; } returnDateTime.MinValue; } /// /// 日期转换 /// publicstaticstringTransformDataLong(DateTime? dateTime) { stringresult =""; if(dateTime.HasValue) { result = dateTime.Value.ToString("yyyy-MM-dd HH:mm:ss"); } returnresult; } /// /// 日期转换 /// publicstaticstringTransformDataShort(DateTime? dateTime) { stringresult =""; if(dateTime.HasValue) { result = dateTime.Value.ToString("yyyy-MM-dd"); } returnresult; } /// /// 将日期转换成decimal /// publicstaticdecimalTransDateTimeToDecimal(DateTime date) { decimalret = 0; ret = Convert.ToDecimal(date.ToString("yyyyMMddHHmmss")); returnret; } /// /// 将decimal转换成日期格式 /// /// yyyyMMddHHmmss /// publicstaticstringTransDecimalToDateTime(stringdate) { DateTimeFormatInfo dtfi =newCultureInfo("zh-CN",false).DateTimeFormat; DateTime dateTime = DateTime.Now; DateTime.TryParseExact(date,"yyyyMMddHHmmss", dtfi, DateTimeStyles.None,outdateTime); returndateTime.ToString("yyyy-MM-dd HH:mm:ss"); ; } } |