0

I have to parse String to Date format(dd.MM.YYYY).

Here is my code:

Date date = null;
try {
    date = new SimpleDateFormat("dd.MM.yyyy").parse(regDate);
} catch (Exception e) {
    System.out.println(e);
}
System.out.println(date);

But the output is: Tue Oct 12 00:00:00 EEST 2021. How can I change my code to print the date in the required format?

Enchantres
  • 853
  • 2
  • 9
  • 22
  • 2
    That's the format you've used for parsing--you're left with a `Date` and its default output format. If you want to format the *output* then you need to format that as well. A `Date` is a representation of time, not a format of that time. – Dave Newton Jun 21 '21 at 18:41
  • 1
    I strongly recommend you don’t use `Date` and `SimpleDateFormat`. Those classes are poorly designed and long outdated, the latter in particular notoriously troublesome. Instead use `LocalDate` and `DateTimeFormatter`, both from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). See for example [my answer](https://stackoverflow.com/a/54649203/5772882) under the linked original question. – Ole V.V. Jun 21 '21 at 21:05
  • 1
    If `dtf` is a `DateTimeFormatter.ofPattern("dd.MM.yyyy")`, then you may use `LocalDate.parse("12.10.2021", dtf).format(dtf)` for getting `12.10.2021` back. – Ole V.V. Jun 21 '21 at 21:12

1 Answers1

-1

Try By using - or / in place of "."

date = new SimpleDateFormat("dd-MM-yyyy").parse(regDate);

or

date = new SimpleDateFormat("dd/MM/yyyy").parse(regDate);
Dave Newton
  • 158,873
  • 26
  • 254
  • 302