Get the App
SLTechnology News&Howtos  ›  Development  › 

Example Analysis of date format Transformation in Java

Shulou Source: shulou.com Published: 2022-06-03 12:29:39 09月23日 Update

This article mainly introduces the Java date format conversion example analysis, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let Xiaobian take you to understand.

Date format conversion is a common problem in the development process.

For example, dates in the following format: 13.06.2017, 2017-06-13, June 13, 2017.

Dates in a fixed format can be formatted into the desired format by string interception, but it is not generic enough.

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

Public static class CovertDateFormatExtensionMethod {/ date string conversion / date string / / original date format / converted date format / 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"; / / yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy 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 ("yyy year MM month dd date", "yyyy-MM-dd") Console.WriteLine (string.Format ("original date: {0}, converted date: {1}", date4, date4.Convert ("yyy year M month dd date", "yyyy-MM-dd")); Console.ReadKey ();}}

Test results:

Thank you for reading this article carefully. I hope the article "sample Analysis of date formatting conversion in Java" shared by the editor will be helpful to you. At the same time, I also hope you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!

Tags: Date format original article character string example analysis test not enough code value interest at the same time way method more friends knowledge results Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Information Linux MariaDB vpn macOS