The calendar hour is set to 0, but displays 1, why?

I am having a weird issue with Java Calendar.

The following code adds 3 hours in a row from a date starting at midnight.

public static void main(String[] args) { Calendar now = Calendar.getInstance(TimeZone.getTimeZone("GMT+0")); // Setting to January 29th, 1920 at 00:00:00 // now.setTimeZone(TimeZone.getTimeZone("GMT+0")); now.set(Calendar.YEAR, 1920); now.set(Calendar.MONTH, 0); now.set(Calendar.DAY_OF_MONTH, 29); now.set(Calendar.HOUR_OF_DAY, 0); now.set(Calendar.MINUTE, 0); now.set(Calendar.SECOND, 0); now.set(Calendar.MILLISECOND, 0); now.setLenient(false); int threeHours = 1000 * 60 * 60 * 3; SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS"); for (int i=0;i<25;i++) { System.out.println(sdf.format(now.getTime())); now.add(Calendar.MILLISECOND, threeHours); } } 

However, the displayed result:

 1920-01-29 01:00:00 000 1920-01-29 04:00:00 000 1920-01-29 07:00:00 000 1920-01-29 10:00:00 000 1920-01-29 13:00:00 000 1920-01-29 16:00:00 000 1920-01-29 19:00:00 000 1920-01-29 22:00:00 000 1920-01-30 01:00:00 000 1920-01-30 04:00:00 000 1920-01-30 07:00:00 000 1920-01-30 10:00:00 000 1920-01-30 13:00:00 000 1920-01-30 16:00:00 000 1920-01-30 19:00:00 000 1920-01-30 22:00:00 000 1920-01-31 01:00:00 000 1920-01-31 04:00:00 000 1920-01-31 07:00:00 000 1920-01-31 10:00:00 000 1920-01-31 13:00:00 000 1920-01-31 16:00:00 000 1920-01-31 19:00:00 000 1920-01-31 22:00:00 000 1920-02-01 01:00:00 000 

Why is the first hour 1 and not 0? I am in GMT + 1, can this be related?

+4
source share
3 answers

Using now.getTime() gets a Date that does not have a time zone.

Try setting the time zone with

 sdf.setTimeZone(now.getTimeZone()); 
+4
source

it should work fine now

  Calendar now = Calendar.getInstance(); TimeZone timezone = TimeZone.getTimeZone("GMT+0"); now.set(Calendar.YEAR, 1920); now.set(Calendar.MONTH, 0); now.set(Calendar.DAY_OF_MONTH, 29); now.set(Calendar.HOUR_OF_DAY, 0); now.set(Calendar.MINUTE, 0); now.set(Calendar.SECOND, 0); now.set(Calendar.MILLISECOND, 0); now.setLenient(false); int threeHours = 1000 * 60 * 60 * 3; SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS"); sdf.setTimeZone(timezone); for (int i=0;i<25;i++) { System.out.println(sdf.format(now.getTime())); now.add(Calendar.MILLISECOND, threeHours); } 
+1
source

I think you should use now.set (Calendar.HOUR, 0); instead of now.set (Calendar.HOUR_OF_DAY, 0);

+1
source

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


All Articles