首页 > 解决方案 > 我想使用 DateTimeFormatterBuilder () 将日期从 String 转换为 LocalDateTime

问题描述

不会将 16 索引下日期的最后一位数字转换为

private LocalDateTime parseDate(String date) {
dateOut = LocalDateTime.parse(date, fmt);

出现错误:

java.time.format.DateTimeParseException:无法在索引 16 处解析文本“27 апр 21, 01:42”

我找不到答案。谢谢您的回答。

public class HtmlParse {

    private LocalDateTime lastDate = null;
    private LocalDateTime dateTime = null;
    private DateTimeFormatter fmt = new DateTimeFormatterBuilder()
            .appendPattern("d ")
            .appendText(ChronoField.MONTH_OF_YEAR, new HashMap<>() { {
                put(1L, "янв"); put(2L,  "фев"); put(3L,  "мар"); put(4L,  "апр");
                put(5L, "май"); put(6L,  "июн"); put(7L,  "июл"); put(8L,  "авг");
                put(9L, "сен"); put(10L, "окт"); put(11L, "ноя"); put(12L, "дек");
            } })
            .appendPattern(" yy, HH:mm")
            .toFormatter(new Locale("ru"));

    public void setLastDate(LocalDateTime lastDate) {
        this.lastDate = lastDate;
    }

    private LocalDateTime parseDate(String date) {
        LocalDateTime dateOut;
            dateOut = LocalDateTime.parse(date, fmt);
        return dateOut;
    }


    public Post detail(String postLink) {
        Post post = null;
        try {
            Document doc = Jsoup.connect(postLink).get();
            String name = doc.title().split(" / Вакансии")[0];
            String text = doc.select("td.msgBody").get(1).text();
            String date = doc.select("td.msgFooter").get(0).text();
            this.dateTime = this.parseDate(date.substring(0, date.indexOf("[")));
            post = new Post(name, text, dateTime, postLink);
        } catch (IOException e) {
            LOG.error(e.getMessage(), e);
        }
        return post;
    }



    public static void main(String[] args) throws SchedulerException {
        String link = "https://www.sql.ru/forum/job-offers/";
        HtmlParse htmlParse = new HtmlParse();
        htmlParse.setLastDate(LocalDateTime.of(2020, 1, 1, 0, 0));
        List<Post> list = htmlParse.parser(link);
        for (Post p : list) {
            System.out.println(p);
        }
    }
}

标签: javajava-time

解决方案



推荐阅读