Convert java.util.Date to String

前端 未结 18 2322
悲&欢浪女
悲&欢浪女 2020-11-22 05:37

I want to convert a java.util.Date object to a String in Java.

The format is 2010-05-30 22:15:52

18条回答
  •  有刺的猬
    2020-11-22 05:52

    Here are examples of using new Java 8 Time API to format legacy java.util.Date:

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss:SSS Z")
            .withZone(ZoneOffset.UTC);
        String utcFormatted = formatter.format(date.toInstant()); 
    
        ZonedDateTime utcDatetime = date.toInstant().atZone(ZoneOffset.UTC);
        String utcFormatted2 = utcDatetime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss:SSS Z"));
        // gives the same as above
    
        ZonedDateTime localDatetime = date.toInstant().atZone(ZoneId.systemDefault());
        String localFormatted = localDatetime.format(DateTimeFormatter.ISO_ZONED_DATE_TIME);
        // 2011-12-03T10:15:30+01:00[Europe/Paris]
    
        String nowFormatted = LocalDateTime.now().toString(); // 2007-12-03T10:15:30.123
    

    It is nice about DateTimeFormatter that it can be efficiently cached as it is thread-safe (unlike SimpleDateFormat).

    List of predefined fomatters and pattern notation reference.

    Credits:

    How to parse/format dates with LocalDateTime? (Java 8)

    Java8 java.util.Date conversion to java.time.ZonedDateTime

    Format Instant to String

    What's the difference between java 8 ZonedDateTime and OffsetDateTime?

提交回复
热议问题