【问题标题】:How to convert 2019-09-18T01:44:35GMT-04:00 to 2019-09-18T01:44:35-04:00 using SimpleDateFormatter如何使用 SimpleDateFormatter 将 2019-09-18T01:44:35GMT-04:00 转换为 2019-09-18T01:44:35-04:00
【发布时间】:2020-01-19 12:23:58
【问题描述】:

我想将日期和时间转换为用户请求的时区。日期和时间采用 GMT 格式。我尝试了解决方案,但最终字符串在结果日期中包含 GMT 字符串,例如 (2019-09-18T01:44:35GMT-04:00)。我不想在结果输出中出现 GMT 字符串。

public static String cnvtGMTtoUserReqTZ(String date, String format, String timeZone) {
    // null check
    if (date == null)
        return null;

    // create SimpleDateFormat object with input format
    SimpleDateFormat sdf = new SimpleDateFormat(format);

    // set timezone to SimpleDateFormat
    sdf.setTimeZone(TimeZone.getTimeZone(timeZone));
    try {
        // converting date from String type to Date type
        Date _date = sdf.parse(date);

        // return Date in required format with timezone as String
        return sdf.format(_date);

    } catch (ParseException e) {
        //log.info("Exception in cnvtGMTtoUserReqTime ::: " + e);
    }
    return null;
}

Actual Output : 2019-09-18T01:44:35GMT-04:00

Expected Output: 2019-09-18T01:44:35-04:00

【问题讨论】:

  • Dude.. 甚至 您使用的格式是什么?请在这里与我们合作..
  • 另外,如果您使用sdf 解析并使用sdf 格式化结果日期,那么什么都不会改变..
  • 如果您只想删除GMT 字符串,为什么还要解析日期。你不能把它从字符串中删除吗?
  • 嗨@DanielBarbarian 我可以用''替换GMT,但我想使用SimpleDateFormatter Calss
  • 您不应该使用SimpleDateFormatTimeZoneDate。这些类设计不佳且过时已久,尤其是第一个类是出了名的麻烦。而是使用DateTimeFormatterZoneId 和来自java.time, the modern Java date and time API 的其他类。

标签: java datetime timezone gmt


【解决方案1】:

处理日期时间对象,而不是字符串

您的问题以错误的方式提出,这很可能是由于您的程序存在设计缺陷。 您不应在程序中将日期和时间作为字符串处理。 始终将日期和时间保存在正确的日期时间对象中,例如 InstantOffsetDateTimeZonedDateTime。上述类来自 java.time,现代 Java 日期和时间 API,它是我们保存和处理日期时间数据的最佳工具。

所以您的问题可能会变成:如何将时间转换为用户请求的时区?时间由Instant 对象表示。而问题的答案是:

    ZoneId userRequestedTimeZone = ZoneId.of("America/New_York");

    Instant moment = Instant.parse("2019-09-18T05:44:35Z");
    ZonedDateTime userDateTime = moment.atZone(userRequestedTimeZone);
    System.out.println(userDateTime);

请用我放置 America/New_York 的用户所需的时区替换。始终以这种格式给出时区 (region/city)。 sn-p 的输出如下:

2019-09-18T01:44:35-04:00[美国/纽约]

假设您不想要输出的 [America/New_York] 部分,请将日期时间格式化为您想要的字符串:

    String dateTimeWithNoZoneId = userDateTime.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME);
    System.out.println(dateTimeWithNoZoneId);

2019-09-18T01:44:35-04:00

后一个输出是 ISO 8601 格式。这种格式有利于序列化,也就是说,如果您需要将日期时间转换为机器可读的文本格式,例如用于持久性或与其他系统交换。虽然也是人类可读的,但它不是您的用户喜欢看到的。正如我所说,这当然不是您应该在程序中处理和处理的内容。

链接

【讨论】:

    【解决方案2】:

    使用这些格式:
    fromFormat = "yyyy-mm-dd'T'HH:mm:sszXXX"
    toFormat = "yyyy-mm-dd'T'HH:mm:ssXXX"

    For more details see examples listed here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-26
      • 2020-07-17
      • 2021-11-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多