java - 如果定义了时区,则 Calendar.getTime() 不返回 UTC 日期

标签 java datetime calendar timezone

我已经为我的日历实例完成了此操作以返回 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/

相关文章:

java - 如何使用 Apache POI 使用自定义列表中的 XDDFDataSource 值创建饼图和条形图

java - 将灰度图像转换为 RGB

java - JDK和JRE版本混淆

python - 如何以 YYYY-Qx 格式查找上一年的匹配值?

python - 从 2 个浮点列创建日期时间列

java - 获取两个相同日期时间的长值会产生不同的值

calendar - 日历服务器需要哪些协议(protocol)

java - 导出带有希伯来字符的 CSV,可由 Excel 打开

rest - Flutter:DateTime 作为改造方法中的参数; DateTime ISO 8061 序列化;改造日期iso8061格式

java - 在java中的日历实例中减去小时作为字符串