Time for someone to provide the modern answer. The other answers were good answers when the question was asked in 2013 and are still correct. Today there is no reason why you should struggle with the old, outdated and simultaneously notoriously troublesome SimpleDateFormat
class. java.time
, the modern Java date and time API, is so much nicer to work with:
DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("M/d/yy");
LocalDate date1 = LocalDate.parse("9/30/11", inputFormatter);
System.out.println(date1);
This prints
2011-09-30
The LocalDate
class represents a date without time-of-day, exactly what you need, it matches your requirement much more precisely than the old classes Date
and Calendar
.
The format pattern strings used with DateTimeFormatter
resemble those from SimpleDateFormat
, there are a few differences. You may use uppercase MM
to require two-digit month (like 09 for September) or a single M
to allow the month to be written with one or two digits. Similarly dd
or d
for day of month. yy
denotes two-digit year and is interpreted with base 2000, that is, from 2000 to 2099 inclusive (wouldn’t work for my birthday).
Link: Oracle tutorial Trail: Date Time explaining how to use java.time
.
ZonedDateTime.now().getMonthValue()
– Moise