当我执行以下代码段
时public static void main(String[] args) {
TimeZone timeZoneInd = TimeZone.getTimeZone("Asia/Calcutta");
TimeZone timeZoneAus = TimeZone.getTimeZone("Australia/Adelaide");
Calendar calendarInd = Calendar.getInstance(timeZoneInd);
Calendar calendarAus = Calendar.getInstance(timeZoneAus);
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy-HH:mm:ss SSSS");
System.out.println("Australian time now :" + sdf.format(calendarAus.getTime()));
System.out.println("Indian time now :" + sdf.format(calendarInd.getTime()));
}
为什么两个值都相同?每个打印时间应该与其时区相对应吗?
答案 0 :(得分:1)
这是因为每个Calendar
对象中的时间是相同的。如果要格式化不同时区的日期,则需要在格式对象中设置时区,如下所示:
TimeZone timeZoneInd = TimeZone.getTimeZone("Asia/Calcutta");
TimeZone timeZoneAus = TimeZone.getTimeZone("Australia/Adelaide");
SimpleDateFormat formatInd = new SimpleDateFormat("dd/MM/yyyy-HH:mm:ss SSSS");
formatInd.setTimeZone(timeZoneInd);
SimpleDateFormat formatAus = new SimpleDateFormat("dd/MM/yyyy-HH:mm:ss SSSS");
formatAus.setTimeZone(timeZoneAus);
Calendar calendarInd = Calendar.getInstance(timeZoneInd);
Calendar calendarAus = Calendar.getInstance(timeZoneAus);
System.out.println("Australian time now :" + formatAus.format(new Date()));
System.out.println("Indian time now :" + formatInd.format(new Date()));
calendarAus.set(Calendar.HOUR_OF_DAY, 12);
calendarInd.set(Calendar.HOUR_OF_DAY, 12);
System.out.println("Australian time at noon :" + formatAus.format(calendarAus.getTime()));
System.out.println("Indian time at noon :" + formatInd.format(calendarInd.getTime()));
这对我来说有以下输出:
您应该使用SimpleDateFormat
格式化日期,Calendar
对象应该用于操作日期。