我已经为我的日历实例完成了此操作以返回 UTC 时区的日期:
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:SS Z");
TimeZone tz = TimeZoneUtil.getTimeZone(StringPool.UTC);
formatter.setTimeZone(tz);
Date dtStart = null;
Date dtEnd = null;
try{
dtStart = formatter.parse(formatter.format(startDate.getTime()));
dtEnd = formatter.parse(formatter.format(endDate.getTime()));
}catch (Exception e) {
e.getStackTrace();
}
它工作正常,直到我格式化日历时间戳以返回具有所需时区的字符串日期,但是当我将该字符串日期解析为日期日期时,它再次选择本地时区? 我需要在 UTC 时区中存储 Date 对象。
任何帮助将不胜感激!
最佳答案
你可以使用这个:
Date localTime = new Date();
//creating DateFormat for converting time from local timezone to GMT
DateFormat converter = new SimpleDateFormat("dd/MM/yyyy:HH:mm:ss");
//getting GMT timezone, you can get any timezone e.g. UTC
converter.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println("local time : " + localTime);;
System.out.println("time in GMT : " + converter.format(localTime));
它将给出:
本地时间:2013 年 6 月 21 日星期五 11:55:00 UTC
GMT 时间:21/06/2013:11:55:00
希望对您有所帮助。
干杯。
关于java - 如果定义了时区,则 Calendar.getTime() 不返回 UTC 日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17233905/