Не хочет парсить даты из файла

141
20 июня 2019, 00:30
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

public class lab8_2 {
    public static void main(String[] args) throws IOException {
        BufferedReader reader = new BufferedReader(new FileReader("date.txt"));
        String line;
        List<LocalDateTime> lines = new ArrayList<>();
        while ((line = reader.readLine()) != null) {
            DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            lines.add(LocalDateTime.parse(line, format));
        }
    }
}

Файл date.txt :

2003-01-06
2004-09-18
2011-10-13
2013-02-08
2015-11-01

Exception in thread "main" java.time.format.DateTimeParseException: Text '2003-01-06' could not be parsed at index 0 at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949) at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851) at java.time.LocalDateTime.parse(LocalDateTime.java:492) at labs.lab8_Files.Text_Files.lab8_2.main(lab8_2.java:19)

Пытался менять формат, не помогло

Answer 1

Дату без времени нужно парсить в LocalDate:

public static void main(String[] args) throws IOException {
    BufferedReader reader = new BufferedReader(new FileReader("date.txt"));
    String line;
    List<LocalDate> lines = new ArrayList<>();
    while ((line = reader.readLine()) != null) {
        DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        lines.add(LocalDate.parse(line, format));
    }
}

либо конвертировать в LocalDate в LocalDateTime:

public static void main(String[] args) throws IOException {
    BufferedReader reader = new BufferedReader(new FileReader("date.txt"));
    String line;
    List<LocalDateTime> lines = new ArrayList<>();
    while ((line = reader.readLine()) != null) {
        DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        lines.add(LocalDate.parse(line, format).atStartOfDay());
    }
}
READ ALSO
Label.getHeight возвращает 0, а Label.getPrefHeight возвращает -1

Label.getHeight возвращает 0, а Label.getPrefHeight возвращает -1

Не могу получить высоту лейбла

132
Android Studio не читает аннотации

Android Studio не читает аннотации

Я хочу сделать Веб-сервисНа ПК запускается сам сервис, а андроид телефон используется как клиент В Intellij IDEA все работает, в Android Studio ругается...

152
ConfigurationException: Could not locate cfg.xml resource [/hibernate.cfg.xml]

ConfigurationException: Could not locate cfg.xml resource [/hibernate.cfg.xml]

Выводит исключение ConfigurationException: Could not locate cfgxml resource [/hibernate

144
Работа с Jetty Servlets Java

Работа с Jetty Servlets Java

Есть основная задача - добавить к основному проекту jetty default servlet, который бы парсил файлы markdown в htmlТк первый раз сталкиваюсь с сервлетами,...

146