您的位置:首页 > 编程语言 > Java开发

Java 8 – How to parse date with "dd MMM" (02 Jan), without year?

2020-03-19 20:07 543 查看

【今日推荐】:为什么一到面试就懵逼!>>>

https://mkyong.com/java8/java-8-how-to-parse-date-with-dd-mmm-02-jan-without-year/


This example shows you how to parse a date (02 Jan) without a year specified.

JavaDateExample.java
package com.mkyong.time;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class JavaDateExample {

public static void main(String[] args) {

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd MMM", Locale.US);

String date = "02 Jan";

LocalDate localDate = LocalDate.parse(date, formatter);

System.out.println(localDate);

System.out.println(formatter.format(localDate));

}

}

Output

Exception in thread "main" java.time.format.DateTimeParseException: Text '02 Jan' could not be parsed: Unable to obtain LocalDate from TemporalAccessor: {DayOfMonth=2, MonthOfYear=1},ISO of type java.time.format.Parsed
at java.base/java.time.format.DateTimeFormatter.createError(DateTimeFormatter.java:2017)
at java.base/java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1952)
at java.base/java.time.LocalDate.parse(LocalDate.java:428)
at com.mkyong.time.JavaDateExample.main(JavaDateExample.java:20)
Caused by: java.time.DateTimeException: Unable to obtain LocalDate from TemporalAccessor: {DayOfMonth=2, MonthOfYear=1},ISO of type java.time.format.Parsed
at java.base/java.time.LocalDate.from(LocalDate.java:396)
at java.base/java.time.format.Parsed.query(Parsed.java:235)
at java.base/java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1948)
... 2 more

Solution

The pattern dd MMM is not enough; we need a DateTimeFormatterBuilder to provide a default year for the date parsing.

JavaDateExample.java
package com.mkyong.time;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.temporal.ChronoField;
import java.util.Locale;

public class JavaDateExample {

public static void main(String[] args) {

DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.appendPattern("dd MMM")
.parseDefaulting(ChronoField.YEAR, 2020)
.toFormatter(Locale.US);

String date = "02 Jan";

LocalDate localDate = LocalDate.parse(date, formatter);

System.out.println(localDate);

System.out.println(formatter.format(localDate));

}

}

Output

2020-01-02
02 Jan

References

java 8 java.time parse date
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  h2 java bash
相关文章推荐