I'm trying to print all the hours of the day using a for loop and incrementing a Date object.
But I can't have "Sun Mar 25 02:00:00", I only have these:
Sun Mar 25 01:00:00 CET 2012
Sun Mar 25 03:00:00 CEST 2012
Sun Mar 25 03:00:00 CEST 2012
Sun Mar 25 04:00:00 CEST 2012
Sun Mar 25 05:00:00 CEST 2012
I'm not interested in having the TimeZone.
I think that the problem is due to the Daylight Saving, but I need the "Sun Mar 25 02:00:00".
How can I do to create that date?
You probably want a DateFormat object that is set up for UTC (which does not observe daylight savings), using a calendar set to UTC will also simplify things quite a bit.
public static void main(String[] args) {
TimeZone utc = TimeZone.getTimeZone("UTC");
Calendar date = Calendar.getInstance(utc);
DateFormat format = DateFormat.getDateTimeInstance();
format.setTimeZone(utc);
date.set(2012, 02, 24, 23, 00, 00);
for (int i = 0; i < 10; i++) {
System.out.println(format.format(date.getTime()));
date.add(Calendar.HOUR_OF_DAY, 1);
}
}
This provides the following output:
Mar 24, 2012 11:00:00 PM
Mar 25, 2012 12:00:00 AM
Mar 25, 2012 1:00:00 AM
Mar 25, 2012 2:00:00 AM
Mar 25, 2012 3:00:00 AM
Mar 25, 2012 4:00:00 AM
Mar 25, 2012 5:00:00 AM
Mar 25, 2012 6:00:00 AM
Mar 25, 2012 7:00:00 AM
Mar 25, 2012 8:00:00 AM
Of course, you can use the formatter to format your date however you like.
The Calendar
class allows you to specify a time zone when you convert Date
values. See the API doc