199

How do I get the month as an integer from a Date object (java.util.Date)?

9
  • 25
    actually getMonth() on Date is deprecated since forever ;) Commented Aug 24, 2011 at 22:20
  • 6
    @slhck: Deprecated. As of JDK version 1.1, replaced by Calendar.get(Calendar.MONTH).
    – adarshr
    Commented Aug 24, 2011 at 22:20
  • 4
    @Zenzen I don't see the problem in using a deprecated method in a mostly deprecated class.
    – Serabe
    Commented Aug 24, 2011 at 22:22
  • 1
    @Muhd if you are working with dates, help yourself and use joda or any other library.
    – Serabe
    Commented Aug 24, 2011 at 22:23
  • 1
    @Serabe: the problem is that there are better solutions (ones that at least aren't deprecated). And getMonth has been deprecated for like 14 years now and it's been deprecated for a reason. Commented Aug 24, 2011 at 22:40

8 Answers 8

333
java.util.Date date = new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int month = cal.get(Calendar.MONTH);
9
  • 188
    Note that Calendar.MONTH is for no apparent reasons ZERO based, ie January==0. Now that's documented just fine in the API, but it's still confusing as hell for first time users. I've yet to find anyone who could tell me why they went with that - maybe time for a new SO question myself (though I fear there isn't any great background to that :/ )
    – Voo
    Commented Aug 24, 2011 at 22:24
  • 5
    @Voo Date.getMonth() method was zero based, which is probably the main reason Calendar.MONTH is as well.
    – Muhd
    Commented Aug 24, 2011 at 22:37
  • 1
    @Muhd Sure after all it was the replacement. But that only shifts the question around to why was Date.getMonth() zero based? Imo a horrible design, especially since days start at one (they could at least be consistent!). I assume it was just some oversight in a not especially well designed API (both Date and Calendar) to begin with. But maybe there's some precedent - it just seems strange to me and has caused problems to more than one beginner in my experience.
    – Voo
    Commented Aug 24, 2011 at 22:42
  • 2
    Actually it's been asked already here on SO (and not only). The bottom line is tnat it's a result of badly designed API. I mean as you mentioned the whole Date class is a joke. Fun fact is that not only Java suffers from this problem - iirc JavaScript's Date getMonth() also starts with a 0! Commented Aug 24, 2011 at 22:49
  • 1
    @Voo getYear() is also, "for no apparent reasons", subtracted by 1900.
    – Hele
    Commented Aug 6, 2013 at 1:34
88

java.time (Java 8)

You can also use the java.time package in Java 8 and convert your java.util.Date object to a java.time.LocalDate object and then just use the getMonthValue() method.

Date date = new Date();
LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
int month = localDate.getMonthValue();

Note that month values are here given from 1 to 12 contrary to cal.get(Calendar.MONTH) in adarshr's answer which gives values from 0 to 11.

But as Basil Bourque said in the comments, the preferred way is to get a Month enum object with the LocalDate::getMonth method.

6
  • 1
    Good answer. Note to the reader: You may want to specify a time zone rather than rely on the call for default shown in the Answer. A new day (and month) dawns earlier in Paris, for example, than Montréal. If you care specifically about Montréal, the use ZoneId.of( "America/Montreal" ). Commented Jun 21, 2015 at 7:26
  • 1
    I just want to add that there is a great article about the introduction of java.time api oracle.com/technetwork/articles/java/…
    – user813853
    Commented Jun 21, 2015 at 7:55
  • By the way, another note to the reader: You can also get a Month enum object rather than a mere integer number. Month m = localDate.gotMonth(); See LocalDate::getMonth method. Using objects such as this makes your code self-documenting, ensures type-safety, and guarantees valid values. See Enum tutorial by Oracle. Commented Dec 26, 2016 at 22:55
  • 1
    if you use date.toInstant() and you happen to be working with a java.sql.Date (the child of java.util.Date) then you will get an UnsupportedOperationException. Try new java.sql.Date(src.getTime()).toLocalDate()
    – Adam
    Commented Feb 24, 2017 at 14:15
  • 1
    @Adam Much easier to convert to/from java.sql.Date by using the new conversion methods added to that old class. java.sql.Date.valueOf( myLocalDate ) and myJavaSqlDate.toLocalDate() Also, JDBC drivers updated for JDBC 4.2 or later no longer need java.sql types, and can directly address java.time types via the ResultSet::getObject and PreparedStatement::setObject methods. Commented Mar 23, 2017 at 7:55
21

If you use Java 8 date api, you can directly get it in one line!

LocalDate today = LocalDate.now();
int month = today.getMonthValue();
3
  • 2
    is this 0 for january or 1?
    – gumuruh
    Commented Dec 25, 2020 at 3:52
  • This only returns single-digit values i.e. you can't form a mm dd value from it without using date or calendar Commented Feb 5, 2021 at 12:40
  • @gumuruh The docs say: Gets the month-of-year field from 1 to 12. and I can confirm that (returns "5" for today, May 23rd).
    – Neph
    Commented May 23 at 11:59
9

Joda-Time

Alternatively, with the Joda-Time DateTime class.

//convert date to datetime
DateTime datetime = new DateTime(date);
int month = Integer.parseInt(datetime.toString("MM"))

…or…

int month = dateTime.getMonthOfYear();
3
  • 3
    Even simpler, just ask the DateTime object’s for its month. int month = dateTime.getMonthOfYear(); Commented Jul 28, 2014 at 23:16
  • Good call Basil, I have updated the code. However, I like the .toString("MM") as it shows there are more possibilities than just "MM".
    – ssoward
    Commented Jul 29, 2014 at 22:04
  • 1
    This answer ignores the crucial issue of time zone. See my comments on Question and sibling Answer. I suggest passing a DateTimeZone object to that DateTime constructor: DateTimeZone.forID( "America/Montreal" ). Commented Jun 21, 2015 at 7:40
8

tl;dr

myUtilDate.toInstant()                          // Convert from legacy class to modern. `Instant` is a point on the timeline in UTC.
          .atZone(                              // Adjust from UTC to a particular time zone to determine date. Renders a `ZonedDateTime` object. 
              ZoneId.of( "America/Montreal" )   // Better to specify desired/expected zone explicitly than rely implicitly on the JVM’s current default time zone.
          )                                     // Returns a `ZonedDateTime` object.
          .getMonthValue()                      // Extract a month number. Returns a `int` number.

java.time Details

The Answer by Ortomala Lokni for using java.time is correct. And you should be using java.time as it is a gigantic improvement over the old java.util.Date/.Calendar classes. See the Oracle Tutorial on java.time.

I'll add some code showing how to use java.time without regard to java.util.Date, for when you are starting out with fresh code.

Using java.time in a nutshell… An Instant is a moment on the timeline in UTC. Apply a time zone (ZoneId) to get a ZonedDateTime.

The Month class is a sophisticated enum to represent a month in general. That enum has handy methods such as getting a localized name. And rest assured that the month number in java.time is a sane one, 1-12, not the zero-based nonsense (0-11) found in java.util.Date/.Calendar.

To get the current date-time, time zone is crucial. At any moment the date is not the same around the world. Therefore the month is not the same around the world if near the ending/beginning of the month.

ZoneId zoneId = ZoneId.of( "America/Montreal" );  // Or 'ZoneOffset.UTC'.
ZonedDateTime now = ZonedDateTime.now( zoneId );
Month month = now.getMonth(); 
int monthNumber = month.getValue(); // Answer to the Question.
String monthName = month.getDisplayName( TextStyle.FULL , Locale.CANADA_FRENCH );

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

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.

6

If you can't use Joda time and you still live in the dark world :) ( Java 5 or lower ) you can enjoy this :

Note: Make sure your date is allready made by the format : dd/MM/YYYY

/**
Make an int Month from a date
*/
public static int getMonthInt(Date date) {

    SimpleDateFormat dateFormat = new SimpleDateFormat("MM");
    return Integer.parseInt(dateFormat.format(date));
}

/**
Make an int Year from a date
*/
public static int getYearInt(Date date) {

    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy");
    return Integer.parseInt(dateFormat.format(date));
}
1
  • You are the mother! / Είσαι η μάνα!
    – Tzegenos
    Commented Jul 3, 2018 at 20:01
1

If we use java.time.LocalDate api, we can get month number in integer in single line:

import java.time.LocalDate;
...
int currentMonthNumber = LocalDate.now().getMonthValue(); //OR
LocalDate scoringDate = LocalDate.parse("2022-07-01").getMonthValue(); //for String date

For example today's date is 29-July-2022, output will be 7.

1
  • May also use YearMonth.now() or MonthDay.now(). And may pass a ZoneId to the now method to make it clear that the operation is time zone dependent.
    – Anonymous
    Commented Jul 29, 2022 at 16:28
0
Date mDate = new Date(System.currentTimeMillis());
mDate.getMonth() + 1

The returned value starts from 0, so you should add one to the result.

5
  • 7
    2 problems with your answer: one is that you can make a date with current time by doing new Date() without System.currentTimeMillis. The other is that getMonth is deprecated.
    – Muhd
    Commented May 13, 2015 at 15:51
  • @Muhd So what is the best solution?
    – twlkyao
    Commented May 14, 2015 at 10:40
  • @Muhd The System.currentTimeMillis() I added here was to indicate that here is a long type, and you can specific the date.
    – twlkyao
    Commented May 15, 2015 at 4:07
  • 4
    Date::getMonth was already deprecated in Java 1.1 (cs.mun.ca/~michael/java/jdk1.1-beta2-docs/api/…) Commented Jun 15, 2015 at 15:11
  • Deprecated in Java 12 Commented Feb 5, 2021 at 12:43

Not the answer you're looking for? Browse other questions tagged or ask your own question.