Home > Article > Backend Development > Detailed implementation of the public method class for C# date format conversion
This article mainly introduces the public method class of C# to implement date format conversion, and analyzes C#'s conversion methods for various common date formats in the form of complete examples, involving CString , date, and time related operation skills, friends in need can refer to the examples in this article
The public method class for date format conversion in C# is shared with you for your reference. The details are as follows:
Here is a demonstration of some date format conversion in C# (UtilityHandle). .cs), the code is as follows:
/// <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; } /// <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"); ; } }
The above is the detailed content of Detailed implementation of the public method class for C# date format conversion. For more information, please follow other related articles on the PHP Chinese website!