I am having a bit of trouble parsing a string date to a Date object. I use a DateFormat to parse the string, and when I print the value of the date
int year =
LocalDate.parse(
"04/12/2011" ,
DateTimeFormatter.ofLocalizedDate( FormatStyle.SHORT ).withLocale( Locale.US )
).getYear() ;
2011
The troublesome java.util.Date class and its siblings are now supplanted by the excellent java.time classes.
String input = "04/12/2011";
Locale locale = Locale.US;
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDate( FormatStyle.SHORT ).withLocale( locale );
LocalDate ld = LocalDate.parse( input , f );
The java.time classes utilize sane numbering, with:
Interrogate the LocalDate for its constituent parts.
int year = ld.getYear(); // 2011
int month = ld.getMonthValue(); // 4
int dayOfMonth = ld.getDayOfMonth(); // 12
You can even ask for automatically localized name of month and name of day-of-week.
String monthName = ld.getMonth().getDisplayName( TextStyle.FULL_STANDALONE , Locale.CANDA_FRENCH ); // avril
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old date-time classes such as java.util.Date, .Calendar, & java.text.SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to java.time.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP (see How to use…).
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.