I have been using java.util
for all date and calendar representations. But I am facing a strange problem here. Calendar.MONTH
, Calendar.DAY_O
ZonedDateTime rightNow = ZonedDateTime.now(ZoneId.of("Africa/Cairo"));
System.out.println(rightNow.getMonth());
System.out.println(rightNow.getMonthValue());
System.out.println(rightNow.getDayOfMonth());
System.out.println(rightNow.getYear());
System.out.println(rightNow);
Output when running just now was:
FEBRUARY 2 15 2019 2019-02-15T21:15:06.313809+02:00[Africa/Cairo]
The Calendar
class is confusing and suffers from poor design, so no wonder that you’re wondering. Fortunately it was replaced the year after you asked this quesion by ZonedDateTime
and other classes in java.time, the modern Java date and time API. So never use Calendar
again now.
The Calendar
class was trying to be very general, so instead of a getMonth
method, etc., it had the notion of fields that could be read and set. Since it was designed long before Java had enum
s, each field had a number and a named constant for that number. So YEAR
(of era) was 1, MONTH
was 2, etc. To get the value of the field of a Calendar
object you were supposed to call the get
method passing the appropriate named constant, for example rightNow.get(Calendar.MONTH)
. Using just rightNow.MONTH
is a regularly repeated mistake. It just gives you the value of the constant, 2.
Oracle tutorial: Date Time explaining how to use java.time.
System.out.println(rightNow.MONTH);
System.out.println(rightNow.DAY_OF_MONTH);
System.out.println(rightNow.YEAR);
System.out.println(rightNow.getTime());
You are printing Calendar constant values.
If you want values, you need to do get....
Example:
System.out.println(rightNow.get(Calendar.MONTH));
Read Calendar javadoc for more information.
Calendar.MONTH doesn't return the current month. It is a constant whose value is 2.
From the source:
public final static int MONTH = 2;
It is for use as a parameter in Calendar's get method
public int get(int field) {...}
The design of Calendar is from the early days of Java, when many of today's conventions were different, non-existant, or developing. Oracle (and earlier, Sun), would never let an API like the java.util.Calendar API become part of the standard API today.
And, for completeness, use Joda Time instead of Java's Date and Calendar API's.
Calendar now = Calendar.getInstance();
out.println("month now= " + (now.get(Calendar.MONTH)+1));
OR with GregorianCalender:
GregorianCalendar nu = new GregorianCalendar();
int day = nu.get(Calendar.DAY_OF_MONTH);
int month = (nu.get(Calendar.MONTH)+1); //month +1 because january`==0
int year= nu.get(Calendar.YEAR);
int hour= nu.get(Calendar.HOUR_OF_DAY);
int minutes= nu.get(Calendar.MINUTE);
here