有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

特定格式的java解析字符串到日期

我有一个格式为String stringDate = "2019-04-25T07:03:17.428Z";的字符串,需要将其转换为格式为2019-04-25 07:03:17的LocalDateTime对象

我已尝试使用LocalDateTime.parse(stringDate, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")),但出现了以下解析异常:

Exception in thread "main" java.time.format.DateTimeParseException: Text '2019-04-25T07:03:17.428Z' could not be parsed at index 10
    at java.base/java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:2046)
    at java.base/java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1948)
    at java.base/java.time.LocalDateTime.parse(LocalDateTime.java:492)
    at com.company.Main.main(Main.java:12)

转换为特定格式的方法是什么


共 (3) 个答案

  1. # 1 楼答案

    你要求的(但不想要的)

        String stringDate = "2019-04-25T07:03:17.428Z";
        LocalDateTime ldt = LocalDateTime.parse(stringDate, DateTimeFormatter.ISO_OFFSET_DATE_TIME)
                .truncatedTo(ChronoUnit.SECONDS);
        System.out.println(ldt);
    

    输出为

    2019-04-25T07:03:17

    它给你你所说的你想要的,但是正如rzwitserloot在另一个answer中指出的,它没有意义。它忽略字符串中的偏移量Z。偏移量对于将日期和时间解释为时间点至关重要。如果字符串改为2019-04-25T07:03:17.428+13:00,那么即使字符串表示早13个小时的时间点,您仍然会得到相同的输出

    truncatedTo()的调用去掉了秒的分数。如果你能忍受那一秒,那就别打电话了

    你想要什么

    对于更合理的转换:

        ZoneId zone = ZoneId.of("Europe/Zagreb");
        
        Instant pointInTime = Instant.parse(stringDate);
        LocalDateTime ldt = pointInTime.atZone(zone)
                .toLocalDateTime()
                .truncatedTo(ChronoUnit.SECONDS);
    
        System.out.format("Date and time in %s: %s%n", zone, ldt);
    

    Date and time in Europe/Zagreb: 2019-04-25T09:03:17

    现在UTC时间07:03已转换为中欧夏季时间09:03

    编辑:如果您确实需要UTC中的LocalDateTime,例如,对于需要它的数据库列,您可以通过以下方式在代码中明确这一事实:

        LocalDateTime ldt = pointInTime.atOffset(ZoneOffset.UTC)
                .toLocalDateTime()
                .truncatedTo(ChronoUnit.SECONDS);
    
        System.out.format("Date and time in UTC: %s%n", ldt);
    

    Date and time in UTC: 2019-04-25T07:03:17

    你的代码出了什么问题

    为了了解失败的原因,让我们看看您收到的异常消息:

    Text '2019-04-25T07:03:17.428Z' could not be parsed at index 10

    索引10是表示时间部分开始的T的位置。让我们比较一下您的格式模式字符串:yyyy-MM-dd HH:mm:ss。它在时间部分之前有一个空格而不是一个T。这就是例外的原因。如果您需要在模式中指定一个T必须在那里,我们需要将它括在单引号中,例如yyyy-MM-dd'T'HH:mm:ss

  2. # 2 楼答案

    您可以首先使用java解析它。时间即时,然后使用java的即时方法。时间LocalDateTime示例:

    String stringDate = "2019-04-25T07:03:17.428Z";
    var instant = Instant.parse(stringDate);
    var localDateTime = LocalDateTime.ofInstant(instant, ZoneOffset.UTC);
    
  3. # 3 楼答案

    基本上,您的输入不是LDT。这是一个ZDT——Z是一个区域(ZoneDateTime)。因此,不可能将这个字符串直接转换为LDT,这很好,因为这没有意义

    将其转换为ZDT。然后将转换为LDT。这是一个单一的方法调用