Date string format conversion, string format conversion
Date format conversion is a common problem during development.
For example, the date format is 13.06.2017, June 13, 2017, June 13, 2017, and.
You can use string truncation to format a date in a fixed format.
The extension method converts a date from the original format to the required format:
Public static class CovertDateFormatExtensionMethod {// <summary> // convert a date string /// </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. yyyy string date1 = "13.06.2017"; // yyyy/MM/dd string date2 = "June 13, 2017"; // yyyy-MM-dd-string date3 = "January 1 "; // string date4 = "June 13, 2017"; Console. writeLine (string. format ("original date: {0}, converted Date: {1}", date1, date1.Convert ("dd. MM. yyyy "," yyyy-MM-dd "); Console. writeLine (string. format ("original date: {0}, converted Date: {1}", date2, date2.Convert ("yyyy/MM/dd ", "yyyy-MM-dd"); Console. writeLine (string. format ("original date: {0}, converted Date: {1}", date3, date3.Convert ("MM dd, yyyy ", "yyyy-MM-dd"); Console. writeLine (string. format ("original date: {0}, converted Date: {1}", date4, date4.Convert ("yyyy-mm-dd ", "yyyy-MM-dd"); Console. readKey ();}}
Test results: