ZonedDateTime toString compatability with ISO 8601

前端 未结 4 2268
走了就别回头了
走了就别回头了 2021-02-18 23:43

I am trying to ensure that calling toString() on my ZonedDateTime Object will comply with ISO-8601 format.

The documentation for the toSt

4条回答
  •  耶瑟儿~
    2021-02-18 23:52

    I like above JodaStephen's last comment 'or a formatter', since using formatter is more robust regardless of data. The reason is OffsetDateTime toString() skip second unit part when there is no value on second unit and below, so it ends up gives yyyy-MM-ddTHH:mmZ instead of yyyy-MM-ddTHH:mm:ssZ. That can cause trouble if other system expects static format and has no adaptability.

    Below is the code I used for simulating both cases where has no time portion and has it.

    /**
     * This function is design to convert Date object from other system to ISO dateTime String 
     * which will be sent to another system. and using formatter to lock up the format
     * @param date java.util.Date
     * @return 'yyyy-MM-ddTHH:mm:ssZ' format ISO dateTime string
     */
    public String formatIsoUtcDateTime(Date date) {
        if(null == date) {
            return null;
        }
        return ZonedDateTime.ofInstant(date.toInstant(), ZoneId.of("UTC"))
                            .format(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'"));
    }
    
    // no time portion with using formatter
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
    Date date = sdf.parse("20171010");
    System.out.println(formatIsoUtcDateTime(date));
    
    // no time portion with using OffsetDateTime toString
    System.out.println(ZonedDateTime.ofInstant(date.toInstant(), ZoneId.of("UTC")).toOffsetDateTime().toString());
    
    // just current date and probably has at least millisecond, using formatter
    System.out.println(formatIsoUtcDateTime(new Date()));
    
    // just current date and probably has at least millisecond, using OffsetDateTime toString
    // this will print yyyy-MM-ddTHH:mm:ss.SSSZ format
    System.out.println(ZonedDateTime.ofInstant(new Date().toInstant(), ZoneId.of("UTC")).toOffsetDateTime().toString());
    

提交回复
热议问题