Home  >  Article  >  Backend Development  >  Problems often encountered in development-date format conversion.

Problems often encountered in development-date format conversion.

零下一度
零下一度Original
2017-06-23 14:29:231559browse

Date format conversion is a common problem encountered during the development process.

For example, dates in the following formats: 13.06.2017, 2017/06/13, June 13, 2017, June 13, 2017.

For fixed-format dates, you can use string interception to format them into the required format, but it is not versatile enough.

The extension method converts the date from the original format to the required format:

public static class CovertDateFormatExtensionMethod
    {/// <summary>/// 日期字符串转换/// </summary>/// <param name="date">日期字符串</param>/// <param name="fromDateFormat">原始日期格式</param>/// <param name="toDateFormat">转换后日期格式</param>/// <returns></returns>public static string Convert(this string date,string fromDateFormat, string toDateFormat)
        {
            DateTime dateTime = DateTime.ParseExact(date, fromDateFormat,
                System.Globalization.DateTimeFormatInfo.CurrentInfo);return dateTime.ToString(toDateFormat);
        }
    }

The test code is as follows:

class Program
    {static void Main(string[] args)
        {//dd.MM.yyyystring date1 = "13.06.2017";//yyyy/MM/ddstring date2 = "2017/06/13";//yyyy年MM月dd日string date3 = "2017年06月13日";//yyyy年M月dd日string date4 = "2017年6月13日";

            Console.WriteLine(string.Format("原始日期:{0},转换后日期:{1}", date1,
                date1.Convert("dd.MM.yyyy", "yyyy-MM-dd")));
            Console.WriteLine(string.Format("原始日期:{0},转换后日期:{1}", date2,
                date2.Convert("yyyy/MM/dd", "yyyy-MM-dd")));
            Console.WriteLine(string.Format("原始日期:{0},转换后日期:{1}", date3,
                date3.Convert("yyyy年MM月dd日", "yyyy-MM-dd")));
            Console.WriteLine(string.Format("原始日期:{0},转换后日期:{1}", date4,
                date4.Convert("yyyy年M月dd日", "yyyy-MM-dd")));

            Console.ReadKey();
        }
    }

Test result:

The above is the detailed content of Problems often encountered in development-date format conversion.. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn