Home > Software engineering >  Android date is incorrect
Android date is incorrect

Time:12-12

I am using Calendar class to get year, month and day:

Calendar calendar = Calendar.getInstance();

this.current_year = calendar.get(Calendar.YEAR);
this.current_month = calendar.get(Calendar.MONTH);
this.current_day = calendar.get(Calendar.DAY_OF_MONTH);

Toast.makeText(this.context, this.current_year   "-"   this.current_month   "-"   this.current_day, Toast.LENGTH_SHORT).show();

Today is 11 Dec 2021 (2021-12-11). But toast alert shows 2021-11-11. Also I tried to set calendar time to a new Date class but still wrong

CodePudding user response:

Calendar.MONTH returns value start from 0 to 11. (like 0 for Jan, 1 for Feb). So, for showing current month value, you have to 1 in current_month. Your final Toast looks like,

Toast.makeText(this.context, this.current_year   "-"   (this.current_month 1)   "-"   this.current_day, Toast.LENGTH_SHORT).show();

It will show the result you want.

CodePudding user response:

The Answer by Modi is correct.

Furthermore, never use Calendar. That terrible class was built by people who did not understand date-time handling. Along with Date and SimpleDateFormat, these classes were years ago supplanted by the modern java.time classes.

Specify a time zone to determine date. For any given moment the date varies around the globe by time zone. May be tomorrow in Japan

  • Related