我在系统时区创建的日历对象是" EDT"。当我得到cal.getTime();
时,它会打印出EDT的日期。如何以UTC格式获取相同日历的日期?
我只是想使用以下代码段将其转换为字符串
`Calendar cal = Calendar.getInstance();
String definedDate = CalendarUtils.toString(cal, "MM/dd/yyyy");
System.out.println(definedDate);
public static String toString(Calendar cal, String pattern) {
String str = "";
if (cal!= null) {
SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
str = dateFormat.format(cal.getTime());
LOGGER.error("Date : "+str);
}
return str;
}
`
答案 0 :(得分:1)
尝试下面的代码,将DateFormat的时区设置为DateFormat.setTimeZone():
TimeZone timeZone = TimeZone.getTimeZone("UTC");
Calendar calendar = Calendar.getInstance(timeZone);
SimpleDateFormat simpleDateFormat =
new SimpleDateFormat("EE MMM dd HH:mm:ss zzz yyyy", Locale.US);
simpleDateFormat.setTimeZone(timeZone);
System.out.println("Time zone: " + timeZone.getID());
System.out.println("default time zone: " + TimeZone.getDefault().getID());
System.out.println();
System.out.println("UTC: " + simpleDateFormat.format(calendar.getTime()));
System.out.println("Default: " + calendar.getTime());
答案 1 :(得分:0)
使用以下代码段获取日历实例...
Calendar cal= Calendar.getInstance(TimeZone.getTimeZone("UTC"));
或者将时区更改为utc,如下所示......
cal.setTimeZone(TimeZone.getTimeZone("UTC"));
答案 2 :(得分:0)
Calendar c2 = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
c2.set(year, month, date, hourOfDay, minute, second);
System.out.println(sdf.format(c2.getTime()));