Parse string with integer value to date

2020-03-30 07:52发布

问题:

I have a string with this value, for example: "20130211154717" I want it to be like "2013-02-11 15:47:17". How can I do that?

回答1:

You can use two SimpleDateFormat: one to parse the input and one to produce the output:

String input =  "20130211154717";
Date d = new SimpleDateFormat("yyyyMMddhhmmss").parse(input);
String output = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(d);
System.out.println("output = " + output);


回答2:

You can use regular expressions for that:

String formattedDate = plainDate.replaceFirst(
        "(\\d{4})(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})",
        "$1-$2-$3 $4:$5:$6");

Though, I like assylias's SimpleDateFormat answer better. :-)



回答3:

What you want to use for this is a SimpleDateFormat. It has a method called parse()



回答4:

You can use the substring() method to get what you want:

String data = "20130211154717";
String year = data.substring(0, 4);
String month = data.substring(4, 2);
// etc.

and then string them together:

String formatted = year + "-" + month + "-" + . . .