Date string format conversion, string format conversion

Source: Internet
Author: User

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:

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.