Ask for the Gregorian calendar for the hour of the day in java

I use the Gregorian calendar to set a specific date and time for the application using the set function from the Gregorian calendar. When I use the getTime () method, it gives me the correct result, however, when I try to access Hour_Of_Day and Minute, it gives the wrong number.

    Calendar time = new GregorianCalendar();
    time.set(2010, Calendar.JANUARY, 1, 7, 20,0);       
    hour = time.HOUR_OF_DAY;
    minute = time.MINUTE; 

An hour gives an output of 11, and a minute gives a value of 12.
Any suggestions on how to fix this? Thanks

+3
source share
2 answers

Your code simply assigns constants to constant / hour. You need to call Calendar.get (int):

hour = time.get(Calendar.HOUR_OF_DAY);
minute = time.get(Calendar.MINUTE);
+8
source

TL; DR

myGregCal
    .toZonedDateTime()  // Convert from legacy class GregorianCalendar to modern ZonedDateTime.
    .getHour()          // Get hour-of-day, 0-23.

java.time

java.time, .

ZonedDateTime .

GregorianCalendar , .

ZonedDateTime zdt = myGregCal.toZonedDateTime() ;

GregorianCalendar.

ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.of( 2010 , Month.JANUARY , 1 , 7 , 20 , 0 , 0 , z );

, LocalTime.

LocalTime localTime = zdt.toLocalTime() ;

, .

int hour = zdt.getHour();
int minute = zdt.getMinute();

java.time

java.time Java 8 . legacy , java.util.Date, Calendar SimpleDateFormat.

Joda-Time, , java.time.

, . Oracle. Qaru . JSR 310.

java.time?

ThreeTen-Extra java.time . java.time. , Interval, YearWeek, YearQuarter .

0

Source: https://habr.com/ru/post/1742557/


All Articles