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

后端 未结 7 1217
既然无缘
既然无缘 2020-11-22 01:11

Java 8 added a new java.time API for working with dates and times (JSR 310).

I have date and time as string (e.g. \"2014-04-08 12:30\"). How can I obtai

7条回答
  •  广开言路
    2020-11-22 02:05

    Both answers above explain very well the question regarding string patterns. However, just in case you are working with ISO 8601 there is no need to apply DateTimeFormatter since LocalDateTime is already prepared for it:

    Convert LocalDateTime to Time Zone ISO8601 String

    LocalDateTime ldt = LocalDateTime.now(); 
    ZonedDateTime zdt = ldt.atZone(ZoneOffset.UTC); //you might use a different zone
    String iso8601 = zdt.toString();
    

    Convert from ISO8601 String back to a LocalDateTime

    String iso8601 = "2016-02-14T18:32:04.150Z";
    ZonedDateTime zdt = ZonedDateTime.parse(iso8601);
    LocalDateTime ldt = zdt.toLocalDateTime();
    

提交回复
热议问题