Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specific date format from date string in java

I have a date string which is

"20120514045300.0Z"

I'm trying to figure out how to convert this to the following format

"2012-05-14-T045300.0Z"

How do you suggest that I should solve it?

like image 784
Wakaley Avatar asked May 17 '12 07:05

Wakaley


2 Answers

Instead of diving into hard-to-read string manipulation code, you should parse the date into a decent representation and from that representation format the output. If possible, I would recommend you to stick with some existing API.

Here's a solution based on SimpleDateFormat. (It hardcodes the 0Z part though.)

String input = "20120514045300.0Z";

DateFormat inputDF  = new SimpleDateFormat("yyyyMMddHHmmss'.0Z'");
DateFormat outputDF = new SimpleDateFormat("yyyy-MM-dd'-T'HHmmss.'0Z'");

Date date = inputDF.parse(input);
String output = outputDF.format(date);

System.out.println(output);  // Prints 2012-05-14-T045300.0Z as expected.

(Adapted from here: How to get Date part from given String?.)

like image 50
aioobe Avatar answered Oct 11 '22 16:10

aioobe


You need to parse the date and them format it to desirable form. Use SimpleDateFormat to do it. You can also check out this question for more details.

like image 39
Vladimir Ivanov Avatar answered Oct 11 '22 17:10

Vladimir Ivanov