How do I get the month as an integer from a Date object (java.util.Date
)?
-
25actually getMonth() on Date is deprecated since forever ;)– Mateusz DymczykAug 24, 2011 at 22:20
-
6@slhck: Deprecated. As of JDK version 1.1, replaced by Calendar.get(Calendar.MONTH).– adarshrAug 24, 2011 at 22:20
-
4@Zenzen I don't see the problem in using a deprecated method in a mostly deprecated class.– SerabeAug 24, 2011 at 22:22
-
1@Muhd if you are working with dates, help yourself and use joda or any other library.– SerabeAug 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.– Mateusz DymczykAug 24, 2011 at 22:40
8 Answers
java.util.Date date= new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int month = cal.get(Calendar.MONTH);
-
184Note 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 :/ )– VooAug 24, 2011 at 22:24 -
5@Voo Date.getMonth() method was zero based, which is probably the main reason Calendar.MONTH is as well.– MuhdAug 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.– VooAug 24, 2011 at 22:42
-
2Actually 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! Aug 24, 2011 at 22:49
-
1
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.
-
1Good 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" )
. Jun 21, 2015 at 7:26 -
1I just want to add that there is a great article about the introduction of java.time api oracle.com/technetwork/articles/java/…– user813853Jun 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();
SeeLocalDate::getMonth
method. Using objects such as this makes your code self-documenting, ensures type-safety, and guarantees valid values. See Enum tutorial by Oracle. Dec 26, 2016 at 22:55 -
1if you use
date.toInstant()
and you happen to be working with ajava.sql.Date
(the child ofjava.util.Date
) then you will get anUnsupportedOperationException
. Trynew java.sql.Date(src.getTime()).toLocalDate()
– AdamFeb 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 )
andmyJavaSqlDate.toLocalDate()
Also, JDBC drivers updated for JDBC 4.2 or later no longer needjava.sql
types, and can directly addressjava.time
types via theResultSet::getObject
andPreparedStatement::setObject
methods. Mar 23, 2017 at 7:55
If you use Java 8 date api, you can directly get it in one line!
LocalDate today = LocalDate.now();
int month = today.getMonthValue();
-
1
-
This only returns single-digit values i.e. you can't form a mm dd value from it without using date or calendar Feb 5, 2021 at 12:40
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();
-
3Even simpler, just ask the
DateTime
object’s for its month.int month = dateTime.getMonthOfYear();
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".– ssowardJul 29, 2014 at 22:04 -
1This 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" )
. Jun 21, 2015 at 7:40
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?
- Java SE 8, Java SE 9, Java SE 10, and later
- Built-in.
- Part of the standard Java API with a bundled implementation.
- Java 9 adds some minor features and fixes.
- Java SE 6 and Java SE 7
- Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
- Android
- Later versions of Android bundle implementations of the java.time classes.
- For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
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.
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));
}
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.
-
May also use
YearMonth.now()
orMonthDay.now()
. And may pass aZoneId
to thenow
method to make it clear that the operation is time zone dependent.– Ole V.V.Jul 29, 2022 at 16:28
Date mDate = new Date(System.currentTimeMillis());
mDate.getMonth() + 1
The returned value starts from 0, so you should add one to the result.
-
62 problems with your answer: one is that you can make a date with current time by doing
new Date()
withoutSystem.currentTimeMillis
. The other is that getMonth is deprecated.– MuhdMay 13, 2015 at 15:51 -
-
@Muhd The System.currentTimeMillis() I added here was to indicate that here is a long type, and you can specific the date.– twlkyaoMay 15, 2015 at 4:07
-
4Date::getMonth was already deprecated in Java 1.1 (cs.mun.ca/~michael/java/jdk1.1-beta2-docs/api/…) Jun 15, 2015 at 15:11
-