what did I do wrong?
IMHO three things:
- You used the long outdated
Date
class and the equally outdated and notoriously troublesome SimpleDateFormat
. Instead use java.time
, the modern Java date and time API.
- You tried to roll your own date format. For most purposes your users will be happier with Java’s built-in date formats, and they save you the error-prone writing of your own format pattern string.
- As others have already said, you used lowercase
mm
in the format pattern string. This is for minute of hour (format pattern letters are case sensitive). Apparently by coincidence you ran your first snippet at 7 minutes past the hour so it happened to agree with the current month (July).
Allow me first to demonstrate that java.time
is a bit more helpful if you insist on writing your own format pattern and happen to use the wrong case (which happens for most of us from time to time). Sorry I cannot write Scala, you will have to do with Java.
DateTimeFormatter dateFormatterWithWrongCase
= DateTimeFormatter.ofPattern("dd-mm-yyyy");
LocalDate.now(ZoneId.of("America/Chicago")).format(dateFormatterWithWrongCase);
This throws the following:
java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: MinuteOfHour
It tells us we were trying to do something with the minute of hour, which we certainly didn’t intend. While it may not make the cause of the error very obvious at a glance, I prefer this by far over just getting an incorrect result. And the message is rather precise when you think about it since a LocalDate
is a date without time of day and therefore doesn’t have minute of hour.
For getting a nice short date format for your users I suggest:
DateTimeFormatter dateFormatter = DateTimeFormatter
.ofLocalizedDate(FormatStyle.SHORT)
.withLocale(Locale.CANADA_FRENCH);
System.out.println(LocalDate.now(ZoneId.of("America/Chicago")).format(dateFormatter));
Today this printed:
18-07-07
One advantage (and I do mean an advantage) is that the output may be different in a different locale. If I use Locale.US
, I get (M/d/yy):
7/7/18
To use the default locale of your JVM either specify Locale.getDefault()
or just leave out the withLocale
call on the formatter.