In Debug mode I see that the value I'm parsing is equal to "2015-09-01 22:00"
. When I create a Calendar I see that HOUR_OF_DAY
is equal to 22.
However, interval
is equal to 10 instead of 22. Where is an error?
import java.util.Calendar;
import java.text.SimpleDateFormat;
public class HelloWorld{
public static void main(String []args){
try {
Calendar c = Calendar.getInstance();
c.setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm").parse("2015-09-01 22:00"));
int interval = c.get(Calendar.HOUR_OF_DAY-1);
System.out.println(interval);
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
}
You're not asking for the HOUR_OF_DAY
value - you're asking for the HOUR_OF_DAY - 1
value, which actually corresponds to Calendar.HOUR
- the 12-hour version:
Field number for get and set indicating the hour of the morning or afternoon. HOUR is used for the 12-hour clock (0 - 11). Noon and midnight are represented by 0, not by 12. E.g., at 10:04:15.250 PM the HOUR is 10.
Just change your code to
int interval = c.get(Calendar.HOUR_OF_DAY);
... and it will be fine.
See more on this question at Stackoverflow