Parse string with integer value to date

2020-03-30 07:27发布

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?

4条回答
Bombasti
2楼-- · 2020-03-30 07:42

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 + "-" + . . .
查看更多
啃猪蹄的小仙女
3楼-- · 2020-03-30 08:01

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

查看更多
Explosion°爆炸
4楼-- · 2020-03-30 08:02

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

查看更多
仙女界的扛把子
5楼-- · 2020-03-30 08:05

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);
查看更多
登录 后发表回答