Date format conversion is a common problem in the development process.
For example, date in the following format: 13.06.2017, 2017/06/13, June 13, 2017, June 13, 2017.
Dates for fixed formats can be formatted in the format required by string truncation, but not universally available.
The extension method converts the date from the original format to the desired format:
public static class Covertdateformatextensionmethod {//<summary>///date string conversion///</summary>///< param name= "Date" > Date string </param>///<param name= "Fromdateformat" > Original date format </param>///<param Name= "Todateformat" > converted date format </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 year MM month dd day string date3 = "June 13, 2017";// YYYY m month dd Day string date4 = "June 13, 2017"; Console.WriteLine (String. Format ("original date: {0}, date converted: {1}", Date1, date1. Convert ("DD. Mm.yyyy "," Yyyy-mm-dd "))); Console.WriteLine (String. Format ("original date: {0}, date converted: {1}", Date2, date2. Convert ("Yyyy/mm/dd", "YYYY-MM-DD")); Console.WriteLine (String. Format ("original date: {0}, date converted: {1}", Date3, date3. Convert ("yyyy MM month DD Day", "YYYY-MM-DD")); Console.WriteLine (String. Format ("original date: {0}, date converted: {1}", Date4, date4. Convert ("yyyy year m DD Day", "Yyyy-mm-dd"))); Console.readkey (); } }
Test results: