0

I have the following:

Date dateCommence = new SimpleDateFormat("YYYY-MM-DD HH:mm:ss").parse("2021-01-06 00:00:00");

But the dateCommence is the following:

Sun Dec 27 00:00:00 SAST 2020

Question

How do I convert the "2021-01-06 00:00:00" string to a date?

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
Richard
  • 8,193
  • 28
  • 107
  • 228
  • 1
    https://docs.oracle.com/javase/10/docs/api/java/text/SimpleDateFormat.html. You probably need `yyyy-MM-dd` instead. – QBrute Oct 29 '20 at 14:34
  • 4
    Does this answer your question? [SimpleDateFormat producing wrong date time when parsing "YYYY-MM-dd HH:mm"](https://stackoverflow.com/questions/15916958/simpledateformat-producing-wrong-date-time-when-parsing-yyyy-mm-dd-hhmm) – Jakov Oct 29 '20 at 14:35
  • 1
    Besides the fact you've totally missed to check the docs, using an IDE would help too... Pasting your snippet in IntelliJ highlights `YYYY` -> `Uppercase 'YYYY' (week year) pattern is used: probably 'yyyy' (year) was intended` and `DD` -> `Uppercase 'DD' (day of year) pattern is used: probably 'dd' (day of month) was intended`. – dbl Oct 29 '20 at 14:36
  • 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. Oct 29 '20 at 15:00

1 Answers1

2

You were using the wrong date format mask. From the documentation, Y corresponds to the week year, and D is the day in year.

Try this version:

Date dateCommence = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
    .parse("2021-01-06 00:00:00");
System.out.println(dateCommence);

This prints:

Wed Jan 06 00:00:00 CET 2021
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360