I have this test code below.
Lines /// 1 /// and /// 2 /// are alternatives.
If I use line /// 2 /// the output looks buggy, seems it does not account for the fact that US Boston and UK London do not differ by 5 hours during the whole year. If I use line /// 1 /// it looks OK, seems it accounts for that fact. Why so? Where is the conceptual difference? Why is shifting both dates by 1 day like this (I mean as in /// 2 ///) incorrect?
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.TimeZone;
public class TimeZoneExample02 {
// private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
public static void main(String[] args) {
Calendar bostonTime = Calendar.getInstance(TimeZone.getTimeZone("America/New_York"));
Calendar londonTime = new GregorianCalendar(TimeZone.getTimeZone("Europe/London"));
londonTime.setTimeInMillis(bostonTime.getTimeInMillis());
bostonTime.getTime();
londonTime.getTime();
for (int i=0; i>=-500; i--){
bostonTime.add(Calendar.DATE, -1);
// londonTime.setTimeInMillis(bostonTime.getTimeInMillis()); /// 1 ///
londonTime.add(Calendar.DATE, -1); /// 2 ///
bostonTime.getTime();
londonTime.getTime();
System.out.printf("Boston time: %s", getString(bostonTime));
System.out.print(" /// ");
System.out.printf("London time: %s\n", getString(londonTime));
}
}
private static String getString(Calendar c){
StringBuilder sb = new StringBuilder();
sb.append(c.get(Calendar.YEAR));
sb.append("-");
sb.append(String.format("%02d", c.get(Calendar.MONTH) + 1));
sb.append("-");
sb.append(String.format("%02d", c.get(Calendar.DAY_OF_MONTH)));
sb.append(" ");
sb.append(String.format("%02d", c.get(Calendar.HOUR_OF_DAY)));
sb.append(":");
sb.append(String.format("%02d", c.get(Calendar.MINUTE)));
sb.append(":");
sb.append(String.format("%02d", c.get(Calendar.SECOND)));
sb.append(".");
return sb.toString();
}
}
OUTPUT 1:
Boston time: 2013-10-30 18:51:12. /// London time: 2013-10-30 22:51:12.
Boston time: 2013-10-29 18:51:12. /// London time: 2013-10-29 22:51:12.
Boston time: 2013-10-28 18:51:12. /// London time: 2013-10-28 22:51:12.
Boston time: 2013-10-27 18:51:12. /// London time: 2013-10-27 22:51:12.
Boston time: 2013-10-26 18:51:12. /// London time: 2013-10-26 23:51:12.
Boston time: 2013-10-25 18:51:12. /// London time: 2013-10-25 23:51:12.
Boston time: 2013-10-24 18:51:12. /// London time: 2013-10-24 23:51:12.
OUTPUT 2:
Boston time: 2013-10-30 18:50:53. /// London time: 2013-10-30 23:50:53.
Boston time: 2013-10-29 18:50:53. /// London time: 2013-10-29 23:50:53.
Boston time: 2013-10-28 18:50:53. /// London time: 2013-10-28 23:50:53.
Boston time: 2013-10-27 18:50:53. /// London time: 2013-10-27 23:50:53.
Boston time: 2013-10-26 18:50:53. /// London time: 2013-10-26 23:50:53.
Boston time: 2013-10-25 18:50:53. /// London time: 2013-10-25 23:50:53.
Boston time: 2013-10-24 18:50:53. /// London time: 2013-10-24 23:50:53.