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
Advertisement
Answer
tl;dr
I am using
Calendar
class
Donβt.
Use only java.time classes.
LocalDate.now( ZoneId.systemDefault() ).getYear()
2021
Details
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 π―π΅ while simultaneously yesterday in Canada π¨π¦.
ZoneId z = ZoneId.of( "Asia/Tokyo" ) ; LocalDate ld = LocalDate.now( z ) ;
Interrogate for parts.
Unlike the legacy classes, the java.time classes use sane numbering. Year 2021 is 2021, and so on. Months are 1-12 for January through December.
int year = ld.getYear() ; int month = ld.getMonthValue() ; int day = ld.getDayOfMonth() ;