I have been playing with calendar, timezones, and conversion since yesterday. This thing has got me all confused. Here is my code:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import java.util.logging.Level;
import java.util.logging.Logger;
class Dates {
public static void main(String[] args) {
test1();
test2();
}
private static void test1() {
String dateString = "2013-10-06T16:25";
String pattern = "yyyy-MM-dd'T'HH:mm";
SimpleDateFormat dtf = new SimpleDateFormat(pattern);
long mil;
Date date;
try {
date = dtf.parse(dateString);
mil = date.getTime();
System.out.println("Create date:" + date);
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(mil);
System.out.println ("millis:"+ mil);
printCal ("Default Cal:", cal);
} catch (ParseException ex) {
Logger.getLogger(Dates.class.getName()).log(Level.SEVERE, null, ex);
}
}
private static void test2() {
// TODO Auto-generated method stub
long ms = 1381091100000L;
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("Americas/New_York"));
cal.setTimeInMillis(ms);
printCal ("EST: ", cal);
}
private static void printCal(String str, Calendar cal) {
// TODO Auto-generated method stub
System.out.println(str+"Year:" + cal.get(Calendar.YEAR) + ", Month:"
+ cal.get(Calendar.MONTH) + ", Date:"
+ cal.get(Calendar.DATE) + ", Hour:"
+ cal.get(Calendar.HOUR) + ", Minutes:"
+ cal.get(Calendar.MINUTE) + ", Seconds:"
+ cal.get(Calendar.SECOND) + ", AM_PM: +"+ cal.get(Calendar.AM));
}
}
The output:
Create date:Sun Oct 06 16:25:00 EDT 2013
millis:1381091100000
Default Cal:Year:2013, Month:9, Date:6, Hour:4, Minutes:25, Seconds:0, AM_PM: +1
EST: Year:2013, Month:9, Date:6, Hour:8, Minutes:25, Seconds:0, AM_PM: +1
As you can see, I am using the same millis in test2() that I get from the test1(). The Hour in test 1 is the expected 4 while in test2 it is 8! What is causing this problem?
Thanks.
Your "Default Cal" prints time in your local timezone: EDT (-4) Your "EST" calendar prints time in UTC/GMT timezone, because "Americas/New_York" is incorrect (extra "s"), it should be "America/New_York", since it's incorrect, TimeZone.getTimeZone(...) returns UTC