0

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?

Mureinik
  • 297,002
  • 52
  • 306
  • 350
user2968192
  • 21
  • 1
  • 5

3 Answers3

3

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);
Mureinik
  • 297,002
  • 52
  • 306
  • 350
3

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

Val
  • 207,596
  • 13
  • 358
  • 360
1

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)
Community
  • 1
  • 1
TheStoneFox
  • 3,007
  • 3
  • 31
  • 47