尝试在Java 8中将日期和时间字符串转换为ISO日期和时间字符串

时间:2018-04-12 18:19:12

标签: java datetime-format

我从数据库20180309220001获取关注字符串的日期和时间 我试图将此DateTime字符串转换为以下模式 - 目标模式2016-10-06T00:00:00-04:00

为了实现上述模式,我编写了以下java方法

 public static String dateConvertorISO(String dateAndTimeStamp) {
        try {
            LocalDateTime originalLocalDateTimeStamp = LocalDateTime.parse(dateAndTimeStamp,
                    DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
            ZoneId usEastern = ZoneId.of("America/New_York");
            return ZonedDateTime.of(originalLocalDateTimeStamp, usEastern).toString();
        } catch (Exception e) {
            LOGGER.error("Cannot convert date-time: {} to ISO because {}", dateAndTimeStamp, e.getMessage());
        }
        return dateAndTimeStamp;

    }

但我无法匹配模式,上面给出的方法,正在返回以下 - 2018-03-09T22:00:01-05:00[America/New_York]

  • 目标模式是一个示例,而不是给定日期和时间字符串的实际转换

3 个答案:

答案 0 :(得分:3)

而不是toString()使用DateTimeFormatter.ISO_OFFSET_DATE_TIME.format()

    public static String dateConvertorISO(String dateAndTimeStamp) {
    try {
        LocalDateTime originalLocalDateTimeStamp = LocalDateTime.parse(dateAndTimeStamp,
                DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        ZoneId usEastern = ZoneId.of("America/New_York");

        ZonedDateTime zonedDateTime = ZonedDateTime.of(originalLocalDateTimeStamp, usEastern);
        return DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(zonedDateTime);
    } catch (Exception e) {
        LOGGER.error("Cannot convert date-time: {} to ISO because {}", dateAndTimeStamp, e.getMessage());
    }
    return dateAndTimeStamp;
}

答案 1 :(得分:0)

我用它来删除结束时区:

public static void main(String... iArgs)
{
    Calendar vCalendar = Calendar.getInstance();

    Date vDate = vCalendar.getTime();

    ZoneId usEastern =ZoneId.of("US/Eastern");

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

    System.out.println(vDate.toInstant().atZone(amNY));
    //prints 2018-04-12T14:38:46.519-04:00[America/New_York]

    System.out.println(vDate.toInstant().atZone(usEastern));
    //prints 2018-04-12T14:38:46.519-04:00[US/Eastern]

    DateTimeFormatter noTimeZoneFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
    System.out.println(vDate.toInstant().atZone(usEastern).format(noTimeZoneFormatter));

    System.out.println(vDate.toInstant().atZone(amNY).format(noTimeZoneFormatter));

    //prints 2018-04-12T14:38:46
}

答案 2 :(得分:0)

感谢帮助和推动正确的方向,我已将我的方法更新为关注,现在我得到了所需的日期和时间模式。

 public static String dateConvertorISO(String dateAndTimeStamp) {
        try {
            return ZonedDateTime.of(
                    LocalDateTime.parse(dateAndTimeStamp, DateTimeFormatter.ofPattern("yyyyMMddHHmmss")),
                    ZoneId.of("America/New_York")).format(DateTimeFormatter.ISO_OFFSET_DATE_TIME);
        } catch (Exception e) {
            LOGGER.error("Cannot convert date-time: {} to ISO because {}", dateAndTimeStamp, e.getMessage());
        }
        return dateAndTimeStamp;

    }