tl;dr
LocalDate.parse(
"20161205",
DateTimeFormatter.BASIC_ISO_DATE
).format(
DateTimeFormatter.ofPattern("dd-MM-uuuu")
)
05-12-2016
Why 01-49-1970?
I cannot reproduce your exact output so can explain most of it, not all. Probably you’ve confused a couple of your test examples and didn’t get 01-49-1970 from new Date(20161205)
. On my computer I got Date is 01-36-1970
. It’s bad enough.
As others have pointed out, new Date(20161205)
gives you a point in time a little more than 20 000 seconds after the epoch of January 1, 1970 00:00 UTC. In UTC the time is then 5:36:01.205 (AM) on January 1. The time in your time zone probably differs. There are time zones where the date is still December 31, 1969.
But this doesn’t seem to explain how you seem to get an output in the 49th month of 1970, or I in the 36th month. This is because you used lowercase mm
in your format pattern string. mm
is for minute of hour. Uppercase MM
is for month. So the 36 I got matches the minutes in the 5:36:01. There are time zones where the minutes are not the same; but I couldn’t find a time zone where the minute of hour is 49 at this time, so your exact reported output I cannot explain.
How can I solve the problem?
As others have said too, use java.time
, the modern Java date and time API. It is so much nicer to work with.
LocalDate currentDate = LocalDate.of(2016, Month.DECEMBER, 5);
Or from a string:
LocalDate currentDate
= LocalDate.parse("20161205", DateTimeFormatter.BASIC_ISO_DATE);
Format to your desired output:
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd-MM-uuuu");
String strCurrentDate = currentDate.format(dtf);
System.out.println("Date is " + strCurrentDate);
This prints
Date is 05-12-2016
As a bonus java.time will let you know through an exception if you happen to use mm
instead of MM
in the format pattern string above.
Link: Oracle Tutorial: Date Time explaining how to use java.time.