Java convert date format [duplicate]

五迷三道 提交于 2019-12-25 06:59:58

问题


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?


回答1:


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



回答2:


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




回答3:


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)


来源:https://stackoverflow.com/questions/31624828/java-convert-date-format

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!