简体   繁体   中英

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?

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? .)

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.

You don't necessarily have to use a DateFormat for something as simple as this. You know what the format of the original date string is and you don't need a Date object, you want a String . So simply transform it directly into a String (without creating an intermediary 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 array copying):

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

If you just need to reformat the string, you could use something like so:

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM