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

后端 未结 7 1212
既然无缘
既然无缘 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 01:47

    Let's take two questions, example string "2014-04-08 12:30"

    How can I obtain a LocalDateTime instance from the given string?

    import java.time.format.DateTimeFormatter
    import java.time.LocalDateTime
    
    final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")
    
    // Parsing or conversion
    final LocalDateTime dt = LocalDateTime.parse("2014-04-08 12:30", formatter)
    

    dt should allow you to all date-time related operations

    How can I then convert the LocalDateTime instance back to a string with the same format?

    final String date = dt.format(formatter)
    

提交回复
热议问题