我正在使用Date
和Calendar
类做一个示例,这是我的代码:
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:00Z");
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, 2013);
cal.set(Calendar.MONTH, Calendar.SEPTEMBER);
cal.set(Calendar.DATE, 1);
cal.set(Calendar.HOUR_OF_DAY, 12);
cal.set(Calendar.MINUTE, 15);
Date date = cal.getTime();
TimeZone tz = TimeZone.getTimeZone("IST");
dateFormat.setTimeZone(tz);
String actual = dateFormat.format(date);
System.out.println(actual);
我希望得到结果
2013-09-01 12:15:00+0530
,但返回的值是2013-09-01 15:45:00+0530
,我不知道为什么。 最佳答案
我要移动一些东西
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:00Z");
TimeZone tz = TimeZone.getTimeZone("IST"); // <-- Move this here.
Calendar cal = Calendar.getInstance();
cal.setTimeZone(tz); // <-- So we can use it here.
cal.set(Calendar.YEAR, 2013);
cal.set(Calendar.MONTH, Calendar.SEPTEMBER);
cal.set(Calendar.DATE, 1);
cal.set(Calendar.HOUR_OF_DAY, 12);
cal.set(Calendar.MINUTE, 15);
Date date = cal.getTime();
dateFormat.setTimeZone(tz); // <-- And here.
然后,您的代码将产生预期的输出。那是
2013-09-01 12:15:00+0530