java.time
Don’t use Date
and SimpleDateFormat
. Those classes are poorly designed and long outdated, the latter in particular notoriously troublesome. As Jon Skeet said, move to java.time, the modern Java date and time API, for a better experience.
DateTimeFormatter dateFormatter
= DateTimeFormatter.ofPattern("d MMM u", Locale.ENGLISH);
LocalDate ld = LocalDate.of(2019, Month.JUNE, 1);
System.out.println(ld.format(dateFormatter));
Output from this snippet is:
1 Jun 2019
A number of format pattern letters including M
for month can yield either a number or a text depending on how many letters you put in the format pattern string (this is true for both DateTimeFormatter
and the legacy SimpleDateFormat
). So MM
gives you two-digit month number, while MMM
gives you a month abbreviation (often three letters, but could be longer or shorter in some languages).
If you are getting an old-fashioned Date
object from a legacy API that you either cannot change or don’t want to upgrade just now, you may convert it like this:
Date accessExpiryDate = getFromLegacyApi();
LocalDate ld = accessExpiryDate.toInstant()
.atZone(ZoneId.systemDefault())
.toLocalDate();
The rest is as before. And now you’ve embarked on using the modern API and can migrate your code base in this direction at your own pace.
Link: Oracle tutorial: Date Time explaining how to use java.time.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…