【问题标题】:Convert GMT time to specific String Format [duplicate]将 GMT 时间转换为特定的字符串格式 [重复]
【发布时间】:2018-01-14 22:49:43
【问题描述】:

我有特定的情况,我必须获取日期字段,将其转换为 GMT 时间,然后将其转换为特定的字符串格式。

这给出了 GMT 时间:

public static void main(String[] args) {        
    Date rightNow = Calendar.getInstance().getTime();
    DateFormat gmtFormat = new SimpleDateFormat();
    TimeZone gmtTime = TimeZone.getTimeZone("GMT");
    gmtFormat.setTimeZone(gmtTime);
    System.out.println("GMT Time: " + gmtFormat.format(rightNow));
    String gmtDate=gmtFormat.format(rightNow);
}

现在我需要将该 GMT 时间转换为字符串格式 yyyy-MM-ddTHH:mm:ssZ 我所在时区的当前时间示例为17:10:00,格林威治标准时间为15:10:00,因此这意味着最终输出应为2017-08-07T15:10:00Z

我尝试使用此代码添加:

String pattern = "yyyy-MM-ddTHH:mm:ssZ";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
String date = simpleDateFormat.format(gmtDate);
System.out.println(date);

当然我得到了异常,因为字符串不能像这样转换,但我需要类似的东西。

【问题讨论】:

  • 使用旧的日期/时间 API 吗? java.time 包要好得多。除此之外,尚不清楚您遇到了什么异常或在哪里......
  • 嗨,我在这一行遇到异常: SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);线程“主”java.lang.IllegalArgumentException 中的此异常:java.text.SimpleDateFormat.compile(Unknown Source) at java.text.SimpleDateFormat.initialize(Unknown Source) 处的非法模式字符 'T'
  • 对,那你调查过吗?基本上你的模式被打破了——你需要引用TZ
  • 正确的模式,如副本中完整的工作示例所示是public static final String ISO_8601_24H_FULL_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX";,根据ISO_8601#Combined_date_and_time_representations不要按照其他人的建议在末尾硬编码Z

标签: java date datetime gmt


【解决方案1】:

将您的 2 个代码块合并在一起:

public static void main(String[] args) {        
  Date rightNow = Calendar.getInstance().getTime();
  String pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ";
  DateFormat gmtFormat = new SimpleDateFormat(pattern);
  TimeZone gmtTime = TimeZone.getTimeZone("GMT");
  gmtFormat.setTimeZone(gmtTime);
  System.out.println("GMT Time: " + gmtFormat.format(rightNow));
}

"yyyy-MM-dd'T'HH:mm:ss.SSSXXX" JavaDoc...

【讨论】:

  • 这不起作用:线程“主”java.lang.IllegalArgumentException 中的异常:java.text.SimpleDateFormat.compile(Unknown Source) at java.text.SimpleDateFormat 处的非法模式字符“T”。在 java.text.SimpleDateFormat.(Unknown Source) at java.text.SimpleDateFormat.(Unknown Source) at ibis.test.EricssonDate.main(EricssonDate.java:34) 处初始化(未知源)跨度>
  • 这与我在代码中遇到的异常完全相同
  • 老实说,我只是复制了您的原始模式,看起来并没有工作。由@RobinTopper 更正...
  • 不,他们的编辑也不正确
猜你喜欢
  • 1970-01-01
  • 2020-04-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-13
  • 2016-04-07
  • 2019-11-25
  • 2019-01-02
相关资源
最近更新 更多