Getting Current time of day

2019-08-07 09:17发布

问题:

public void getTime()
{
    Calendar calendar = Calendar.getInstance();
    calendar.getTime();
    this.minutes = calendar.MINUTE;
    this.hours= calendar.HOUR_OF_DAY;

}

Given this code does the variable minutes and hours set to the current time in an integer value? it doesn't seem so is there something wrong?

回答1:

Try this to get the Minutes, and Hour from the Calender instance of Current Day

this.minutes = calendar.get(Calendar.MINUTE);
this.hours= calendar.get(Calendar.HOUR_OF_DAY);

Calendar.MINUTE and Calendar.HOUR_OF_DAY are constants, it only give the int value. Apply the int value to your calendar instance and get the Minute and Hour value.



回答2:

The Calendar class is intended to be used this way:

Calendar calendar = Calendar.getInstance();
this.minutes = calendar.get(Calendar.MINUTE);
this.hours = calendar.get(Calendar.HOUR_OF_DAY);

By the way, the line calendar.getTime(); doesn't do anything since you are not saving the result of getTime in a variable.

I would also recommend to rename the method void getTime() since it is not a getter method (it doesn't return anything).



回答3:

it should be used like this

Calendar calendar = Calendar.getInstance();
this.minutes = calendar.get(Calendar.MINUTE);
this.hours=calendar.get(Calendar.HOUR_OF_DAY);


回答4:

Indeed Calendar calendar = Calendar.getInstance(); does set calendar to the current day. That bit of code is fine.

But calendar.MINUTE and calendar.HOUR_OF_DAY are constant values from an enumeration. That's why you're getting odd results.

You need to supply the enumerator values as parameters to a function: for example

this.minutes = calendar.get(Calendar.MINUTE);
this.hours = calendar.get(Calendar.HOUR_OF_DAY);