Bruno Klein
Bruno Klein

Reputation: 3367

Parse string with integer value to date

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?

Upvotes: 1

Views: 753

Answers (4)

Ted Hopp
Ted Hopp

Reputation: 234847

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 + "-" + . . .

Upvotes: 0

Daniel Kaplan
Daniel Kaplan

Reputation: 67440

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

Upvotes: 0

assylias
assylias

Reputation: 328737

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

Upvotes: 8

C. K. Young
C. K. Young

Reputation: 223123

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

Upvotes: 1

Related Questions