-2

My input string is "22/12/2019" in "dd/MM/yyyy" format. I need to convert this string into Date object while retaining the format. The output still needs to be in dd/MM/yyyy format but it should be a Date object. Please advise

Noob
  • 17
  • 3
  • 1
    Date objects do not have format. – forpas Dec 06 '19 at 20:05
  • Check [DateFormat.parse(String)](https://docs.oracle.com/javase/8/docs/api/java/text/DateFormat.html#parse-java.lang.String-) – Augusto Dec 06 '19 at 20:08
  • `Date` is a class. If you want to preserve the format when you convert the date object back to string, then you should use a formatter. In you case, it doesn't make sense. although it can help assign right values to the object. – Sunil Dabburi Dec 06 '19 at 20:21
  • I recommend you don’t use `Date`. That class is poorly designed and long outdated. Instead use `LocalDate` from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Dec 07 '19 at 08:24
  • *Please advise* I advise you not to care about the format of your `LocalDate` object (that you should use instead of `Date`). Only in your interface worry about formats. And only there format your `LocalDate` into a string in the required format. – Ole V.V. Dec 07 '19 at 08:26

1 Answers1

1
SimpleDateFormat sdf = new SimpleDateFormat("<YOUR FORMAT HERE>");
String dateInString = "15-10-2015 10:20:56";
Date date = sdf.parse(dateInString);
System.out.println(date);

Please find the formatting samples here

Selaka Nanayakkara
  • 3,296
  • 1
  • 22
  • 42
  • Please don’t teach the young ones to use the long outdated and notoriously troublesome `SimpleDateFormat` class. At least not as the first option. And not without any reservation. Today we have so much better in [`java.time`, the modern Java date and time API,](https://docs.oracle.com/javase/tutorial/datetime/) and its `DateTimeFormatter`. – Ole V.V. Dec 07 '19 at 08:18