tl;dr
int monthNumber = LocalDate.now().getMonth().getValue() ; // 1-12 for January-December.
Avoid legacy date-time classes
The other Answers are outmoded. The terribly flawed legacy date-time classes such as Calendar
& Date
were years ago supplanted by the modern java.time classes defined in JSR 310.
java.time
If you want a count of milliseconds since the first moment of 1970 as seen with an offset from UTC of zero hours-minutes-seconds, use java.time.Instant
class.
long millisSinceEpoch = Instant.now().toMillis() ;
Going the other direction:
Instant instant = Instant.ofMillis( millisSinceEpoch ) ;
If you want to know the month, you must specify the time zone by which you want to determine the date. For any given moment, the time and date varies around the globe by time zone. Therefore the month can vary too.
ZoneId z = ZoneId.of( "Asia/Tokyo" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;
Interrogate for the month, an enum object Month
.
Month month = zdt.getMonth() ;
Get the month number by asking the enum object for is definition order. Unlike the legacy Calendar
class, java.time uses sane numbering: 1-12 for January-December. So March is 3, as you expected.
int monthNumber = month.getValue() ;
If you want to skip the count of milliseconds, and just want to know the current month, use LocalDate
to capture the current date.
ZoneId z = ZoneId.of( "Africa/Casablanca" ) ;
LocalDate today = LocalDate.now( z ) ;
Month currentMonth = today.getMonth() ;
int monthNumber = currentMonth.getValue() ;
Or, collapse that code:
int monthNumber =
LocalDate
.now( ZoneId.of( "Africa/Casablanca" ) )
.getMonth()
.getValue() ;