【问题标题】:Need current date is in "UTC" timezone having Date format [duplicate]需要当前日期在具有日期格式的“UTC”时区[重复]
【发布时间】:2016-08-01 12:08:32
【问题描述】:

我试图将当前日期转换为“UTC”时区格式

    Calendar cal = Calendar.getInstance();
    cal.setTime(new Date());
    DateFormat sdf = new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy");
    sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
    String dat = sdf.format(cal.getTime());
    System.out.println("In string format" + dat);
    System.out.println(("Date After parses " + (Date) sdf.parse(dat)));

下面是操作:

字符串格式 Mon Apr 11 09:57:12 +0000 2016 解析后的日期 Mon Apr 11 15:27:12 IST 2016

当我尝试从字符串转换日期格式的日期(解析)时,我得到的日期是当前日期时间,也是 IST 格式。

【问题讨论】:

  • A Date 对象没有与之关联的任何时区...如果您想在特定时区将其打印出来,您需要使用 DateFormat.format() 就像您所做的那样...
  • 我刚刚找到了上述问题的解决方案。我们必须为此更改默认时区。在我的情况下,默认时区是 IST,所以我将其从 UTC 更改。 TimeZone.setDefault(TimeZone.getTimeZone("UTC"));日历 cal = Calendar.getInstance(TimeZone.getTimeZone("UTC")); cal.setTime(new Date());
  • 如果您要更改默认时区只是为了显示Date 对象,那么您做错了...您要在这里解决的问题是什么?为什么要在不使用 DateFormat 的情况下打印出 Date 对象?
  • 我的数据库在 UTC 时区,我的应用程序在 IST 时区。所以我必须每小时从数据库为应用程序生成报告,因为我需要当前时间,它是 UTC 时区格式。
  • @Vaibs 请在发帖前搜索 Stack Overflow。您的问题已经被讨论了数百次。

标签: java date


【解决方案1】:

试试这个post中解释的解决方案

基本上他得到了时区设置为“UTC”的日历实例

代码如下:

 TimeZone timeZone = TimeZone.getTimeZone("UTC");
 Calendar calendar = Calendar.getInstance(timeZone);
 calendar.setTime(new Date());
 DateFormat simpleDateFormat = new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy");
 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());

【讨论】:

    猜你喜欢
    • 2013-06-16
    • 1970-01-01
    • 1970-01-01
    • 2014-08-08
    • 1970-01-01
    • 2019-09-27
    • 2015-11-13
    • 2020-10-08
    • 1970-01-01
    相关资源
    最近更新 更多