0

I have a timestamp 13 Dec 2018 19:37:18 which I need to convert to 2018-12-13 19:37:18, I am following the below steps but it is giving incorrect timestamp

     DateFormat outputFormat = new SimpleDateFormat("YYYY-MM-DD HH:mm:ss");
     DateFormat inputFormat = new SimpleDateFormat("DD MMM YYYY HH:mm:ss");
     Date date = inputFormat.parse(updatedStartime);
     String NewStartTime = outputFormat.format(date); 

I am getting the output as 2018-Jan-01 19:37:18, Do I need to convert the MMM to integer month value before formatting the output? what is the correct step to get the expected output?

SimbuStar
  • 623
  • 1
  • 7
  • 18
  • I recommend you avoid the `SimpleDateFormat` class. It is not only long outdated, it is also notoriously troublesome. Today we have so much better in [`java.time`, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Dec 14 '18 at 07:39
  • `LocalDateTime.parse("13 Dec 2018 19:37:18", DateTimeFormatter.ofPattern("d MMM u H:mm:ss", Locale.ENGLISH)).format(DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss"))` yields `2018-12-13 19:37:18` (please break up into manageable pieces as in your question). – Ole V.V. Dec 14 '18 at 07:50

1 Answers1

2

D is "day in year"; not "day in month" what you actually need, so d.

Y is "week years"; i guess you meant y for normal year

So in all that would be:

    DateFormat outputFormat = new SimpleDateFormat("yyy-MM-dd HH:mm:ss");
    DateFormat inputFormat = new SimpleDateFormat("dd MMM yyyy HH:mm:ss", Locale.US);

For more details look at the javadoc https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

k5_
  • 5,450
  • 2
  • 19
  • 27