如何格式化日期/时间字符串? (JAVA)

嗨,有人可以帮忙吗? 我正在尝试格式化日期和时间字符串。 目前它看起来像这个“ 20160112T110000Z ”,我需要它是“ 2016-01-12T11:00:00Z

不带特殊字符的字符串从第三方重复库返回。 在将其解析为Calendar对象之前,我需要将其转换为具有特殊字符。

有人可以帮忙吗?

到目前为止我的代码看起来像:

  final String TIMEFORMAT = "yyyy-MM-dd'T'HH:mm:ss'Z'"; String string = "20160112T110000Z"; SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); Date date = format.parse(string); System.out.println(date); 

然而,这只是行不通。

任何建议表示赞赏

您必须使用与源匹配的格式读取字符串,这将为您提供正确的Date

然后只需用您想要的格式编写它:

  String string = "20160112T110000Z"; String originalStringFormat = "yyyyMMdd'T'HHmmss'Z'"; String desiredStringFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'"; SimpleDateFormat readingFormat = new SimpleDateFormat(originalStringFormat); SimpleDateFormat outputFormat = new SimpleDateFormat(desiredStringFormat); try { Date date = readingFormat.parse(string); System.out.println(outputFormat.format(date)); } catch (ParseException e) { e.printStackTrace(); }