Let's say I have an instance of a java.util.Date object.
Date date = new Date();
What is the idiomatic way to extract the year and the month? It seems that the methods getMonth and getYear have been deprecated. What should I use instead?
Let's say I have an instance of a java.util.Date object.
Date date = new Date();
What is the idiomatic way to extract the year and the month? It seems that the methods getMonth and getYear have been deprecated. What should I use instead?
Date API in Java really is overcomplicated. You should use
Calendar c = Calendar.getInstance();
c.setTime(date);
c.get(Calendar.MONTH);
c.get(Calendar.YEAR);
The java.util.Date & Calendar classes bundled with Java are notoriously troublesome. Avoid them.
Both the question and other answer ignore the critical issue of time zone. If you neglect to specify a time zone, you will get the JVM's default. That means the results of your code vary when run on different computers or changed JVM settings, probably not what you want.
This third-party open-source library, Joda-Time, is a popular replacement.
Specify a time zone rather than rely on default.
DateTimeZone timeZone = DateTimeZone.forID( "Europe/Paris" );
java.util.Locale locale = java.util.Locale.FRANCE;
DateTime now = new DateTime( timeZone );
int dayOfMonth = now.getDayOfMonth();
int monthOfYear = now.getMonthOfYear(); // 1-based counting, January = 1, unlike java.util.Calendar.
String nowAsString = DateTimeFormat.forStyle( "F-" ).withLocale( locale ).print( now );
Dump to console…
System.out.println( "now: " + now );
System.out.println( "dayOfMonth: " + dayOfMonth );
System.out.println( "monthOfYear: " + monthOfYear );
System.out.println( "nowAsString: " + nowAsString );
When run…
now: 2014-02-21T05:51:18.688+01:00
dayOfMonth: 21
monthOfYear: 2
nowAsString: vendredi 21 février 2014
Java 8 brings a new java.time.8 package to supplant the old j.u.Date/Calendar classes. This new package is inspired by Joda-Time (but re-architected) and defined by JSR 310.
ZoneId zoneId = ZoneId.of( "Europe/Paris" );
ZonedDateTime now = ZonedDateTime.now( zoneId );
int dayOfMonth = now.getDayOfMonth();
int monthOfYear = now.getMonthValue(); // 1-based counting, January = 1, unlike java.util.Calendar.
String nowAsString = DateTimeFormatter.ofLocalizedDate( FormatStyle.FULL ).withLocale( Locale.FRANCE ).format( now );
Dump to console…
System.out.println( "now: " + now );
System.out.println( "dayOfMonth: " + dayOfMonth );
System.out.println( "monthOfYear: " + monthOfYear );
System.out.println( "nowAsString: " + nowAsString );
When run…
now: 2014-02-21T06:05:48.833+01:00[Europe/Paris]
dayOfMonth: 21
monthOfYear: 2
nowAsString: vendredi 21 février 2014