Java 8: Convert file time (milliseconds from 1970) to RFC 1123 format

后端 未结 3 1755
北恋
北恋 2021-01-06 00:45

This seems like it should be simple, but so far nothing I try is working. Basically I want to convert a file time in milliseconds from 1970 (the usual) to a TemporalAccessor

3条回答
  •  清歌不尽
    2021-01-06 01:34

    The conversion to Instant succeeds without problem. The problem is the formatter. Use ISO_INSTANT formatter instead of RFC_1123_DATE_TIME then you should go:

            inst = Instant.now();
            System.out.println(java.time.format.DateTimeFormatter.ISO_INSTANT
                               .format( inst ) );
    

    --> 2015-07-20T21:11:53.001Z

    If you really want to have RFC_1123 format, you have to declare a timezone.

    Either append it to the formatter :

            System.out.println(java.time.format.DateTimeFormatter.RFC_1123_DATE_TIME
                               .withZone( ZoneOffset.UTC )
                               .format( inst ) );
    

    or convert the Instant to a ZonedDateTime:

            ZonedDateTime zdt = ZonedDateTime.ofInstant( inst, ZoneOffset.UTC );
            System.out.println(java.time.format.DateTimeFormatter.RFC_1123_DATE_TIME
                               .format( zdt ) );
    

    --> Mon, 20 Jul 2015 21:11:53 GMT

提交回复
热议问题