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

后端 未结 7 1377
既然无缘
既然无缘 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:03

    Parsing date and time

    To create a LocalDateTime object from a string you can use the static LocalDateTime.parse() method. It takes a string and a DateTimeFormatter as parameter. The DateTimeFormatter is used to specify the date/time pattern.

    String str = "1986-04-08 12:30";
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
    LocalDateTime dateTime = LocalDateTime.parse(str, formatter);
    

    Formatting date and time

    To create a formatted string out a LocalDateTime object you can use the format() method.

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
    LocalDateTime dateTime = LocalDateTime.of(1986, Month.APRIL, 8, 12, 30);
    String formattedDateTime = dateTime.format(formatter); // "1986-04-08 12:30"
    

    Note that there are some commonly used date/time formats predefined as constants in DateTimeFormatter. For example: Using DateTimeFormatter.ISO_DATE_TIME to format the LocalDateTime instance from above would result in the string "1986-04-08T12:30:00".

    The parse() and format() methods are available for all date/time related objects (e.g. LocalDate or ZonedDateTime)

提交回复
热议问题