0

I have Date object Fri Mar 25 14:19:51 PDT 2019

I need to change it to 2019-03-25 14:19:51

I am currently converting in this way,

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

Date date =  Fri Mar 25 14:19:51 PDT 2019 // I have my date as object

DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

String dateString = df.format(date); // 2019-03-25 14:19:51 got result as needed

Date parsed = format.parse(dateString); // Fri Mar 25 14:19:51 PDT 2019 again changed to old format

I need my parsed date object in same format as dateString

Logic
  • 2,230
  • 2
  • 24
  • 41
  • 2
    Here we go again. A Date doesn't have any format. It's just a number of milliseconds. Just like an integer doesn't have any format. It's just a number. You can transform it to a String and, when doing, that, choose a format. Just like you can format the number 2000 as 2,000, 2 000,00, etc. – JB Nizet Mar 25 '19 at 21:34
  • @JBNizet I am trying to format it and I got what I wanted as string, why I re convert it to Date object, it is not getting formatted as I wanted. Could you please look at the code one more time – Logic Mar 25 '19 at 21:43
  • Because a Date has no format at all. It's just a number of milliseconds. If you parse the string "one hundred and twenty two" to transform it to an integer, and then print the integer, what will you get? You'll get 122. Not "one hundred and twenty two". Because an int doesn't have any format. It is just a number. Dame for a Date. – JB Nizet Mar 25 '19 at 21:46
  • I recommend you don’t use `SimpleDateFormat` and `Date`. Those classes are poorly designed and long outdated, the former in particular notoriously troublesome. Instead use `LocalDateTime` and `DateTimeFormatter`, both from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Mar 26 '19 at 08:11

0 Answers0