I tried
Calendar calendar= Calendar.getInstance();
System.out.println("use with command get time "calendar.getTime()" : "+calendar.getTime());
System.out.println("use with command get month "calendar.get(Calendar.MONTH)": "+calendar.get(Calendar.MONTH));
but I can’t get the right month.
How can I get the current month? Thanks for reading and sorry for my bad English.
5
Answers
java.time.LocalDate
You can use below to get month value in int or string
You can also use the
SimpleDateFormat
method to get the current date and time.Here see in my function I get the current date and time for your reference
For more information, you can refer to the official android documentation here
Here are some examples from official documentation. Reference Link
Here
MM
represents months in integer form (dec ~ 12)Here
MMM
represents months in alphabets (Dec)The Answer by Sriram is correct, and provides the modern solution using
java.time.LocalDate
class. Here are a few more details.Time zone
The
LocalDate#now
method implicitly uses the JVM’s current default time zone. Time zone is critical because for any given moment the time, and therefore the date, can vary around the globe by zone. It can be “tomorrow” in Tokyo Japan while simultaneously be “yesterday” in Toledo Ohio US.If you omit passing the
ZoneId
object, the JVM‘S current default time zone is automatically applied. This has the same effect as explicitly passing the default.I recommend the explicit approach to make your intentions crystal-clear.
Month
enumThe method
LocalDate#getMonth
returns aMonth
enum object.If you want to generate text to represent that value, you can automatically localize.
See this code run at Ideone.com.
You can access the JVM’s current default locale by calling
Locale.getDefault()
.Android
Android 26+ carries an implementation of the java.time classes.
For earlier Android, use the latest tooling to access most of the java.time functionality via “API desugaring”.
If you look at the source code for class
java.util.Calendar
, you will find the following constant:Hence
calendar.get(Calendar.MONTH))
correctly returns 11 (eleven).However, Android 8 (API level 26) added class LocalDate which should be used instead of class
Calendar
. Note that classCalendar
contains both date and time whereas classLocalDate
contains the date only. ClassLocalDateTime
contains both a date and a time. There is also classLocalTime
.According to the documentation for [static] method
now
, in classLocalDate
:If you want the current month, you can call method
getMonthValue
which…Alternatively, you can call method
getMonth
which…So your code should be:
which produces the following output: