Lenient Java 8 Date parsing

前端 未结 4 2226
無奈伤痛
無奈伤痛 2020-12-18 04:47

I\'d like to parse \'2015-10-01\' with LocalDateTime. What I have to do is

LocalDate localDate = LocalDate.parse(\'2015-10-01\');
LocalDateTime          


        
4条回答
  •  生来不讨喜
    2020-12-18 05:27

    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:00";
    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)

提交回复
热议问题