Java convert date format [duplicate]

2019-09-14 22:05发布

This question already has an answer here:

I got format like this

25 Jul 2015 07:32:16

and I want it like this

2015-07-25 07:32:16

How can I do it using java?

3条回答
劫难
2楼-- · 2019-09-14 22:40

You could use two SimpleDateFormats - one to parse the string into a Date instance and the other to format it to your desired output.

String input = "25 Jul 2015 07:32:16";
DateFormat parser = new SimpleDateFormat("dd MMM yyyy HH:mm:ss");
Date date = parser.parse(input);
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String output = formatter.format(date);
查看更多
老娘就宠你
3楼-- · 2019-09-14 22:43

You simply need to have two date formatters, one to parse your date in the source format and another to format it in the target format. It goes like this:

SimpleDateFormat fromFmt = new SimpleDateFormat("dd MMM yyyy HH:mm:ss");
Date date = fromFmt.parse("25 Jul 2015 07:32:16");;

SimpleDateFormat toFmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(toFmt.format(date));

You can find an executable version of this code shared here

查看更多
爷、活的狠高调
4楼-- · 2019-09-14 22:54

Look at SimpleDateFormat

http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

It can be used to parse a string to a date

Java string to date conversion

And then used to take that date and reparse it as a different formatted string

http://examples.javacodegeeks.com/core-java/text/java-simpledateformat-example/

something like this

mydate = "25 Jul 2015 07:32:16"

DateFormat format = new SimpleDateFormat("d MM yyyy H:m:s")
Date date = format.parse(mydate)

DateFormat outputFormat = new SimpleDateFormat("yyyy-m-d H:m:s")

String finalOutput = outputFormat.format(date)
查看更多
登录 后发表回答