A specific date format from a date string in java

I have a date string that

"20120514045300.0Z" 

I am trying to figure out how to convert this to the following format

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

How do you suggest me to solve this?

+4
source share
4 answers

Instead of plunging into hard-to-read string manipulation code, you should parse the date in a decent presentation and out of this output presentation format. If possible, I recommend that you stick with some existing API.

Here the solution is based on SimpleDateFormat . (He hardcodes the 0Z part.)

 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 a date from a given string?. )

+8
source

You need to analyze the date, and they will format it in the desired form. Use SimpleDateFormat to do this. You can also check this question for more details.

+2
source

You don't have to use DateFormat for something as simple as this. You know what format the original date string is and you don't need a Date object, you want a String . Therefore, just convert it directly to String (without creating an intermediate Date object) as follows:

 String s = "20120514045300.0Z"; String formatted = s.substring(0, 4) + '-' + s.substring(4, 6) + '-' + s.substring(6, 8) + "-T" + s.substring(8); 

You can even use StringBuilder as follows (although this is a bit inefficient due to copying the array):

 StringBuilder sb = new StringBuilder(s); sb.insert(4, '-').insert(7,'-').insert(10,"-T"); String formatted = sb.toString(); 
0
source

If you just need to reformat the string, you can use something like this:

 String str = "20120514045300.0Z"; Pattern p = Pattern.compile("^(\\d{4})(\\d{2})(\\d{2})(.+)$"); Matcher m = p.matcher(str); if (m.matches()) { String newStr = m.group(1) + "-" + m.group(2) + "-" + m.group(3) + "-T" + m.group(4); System.out.println(newStr); } 
0
source

Source: https://habr.com/ru/post/1412921/


All Articles