use*_*011 6 java jodatime java-8 java-time
使用Joda时间解析借记卡/信用卡的到期日期非常容易:
org.joda.time.format.DateTimeFormatter dateTimeFormatter = org.joda.time.format.DateTimeFormat.forPattern("MMyy").withZone(DateTimeZone.forID("UTC"));
org.joda.time.DateTime jodaDateTime = dateTimeFormatter.parseDateTime("0216");
System.out.println(jodaDateTime);
Run Code Online (Sandbox Code Playgroud)
日期: 2016-02-01T00:00:00.000Z
我尝试使用Java Time API做同样的事情:
java.time.format.DateTimeFormatter formatter = java.time.format.DateTimeFormatter.ofPattern("MMyy").withZone(ZoneId.of("UTC"));
java.time.LocalDate localDate = java.time.LocalDate.parse("0216", formatter);
System.out.println(localDate);
Run Code Online (Sandbox Code Playgroud)
输出:
引起:java.time.DateTimeException:无法从TemporalAccessor获取LocalDate:{MonthOfYear = 2,Year = 2016},ISO,UTC,类型为java.time.format.Parsed,类型为java.time.LocalDate.from(LocalDate.java :368)java.time.format.Parsed.query(Parsed.java:226)at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)... 30 more
我犯了什么错误以及如何解决它?
Tun*_*aki 13
A LocalDate表示由年,月和日组成的日期.LocalDate如果您没有定义这三个字段,则无法创建.在这种情况下,您正在解析一个月和一年,但没有一天.因此,你无法解析它LocalDate.
如果这一天无关紧要,您可以将其解析为一个YearMonth对象:
YearMonth是一个不可变的日期时间对象,表示年和月的组合.
public static void main(String[] args) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMyy").withZone(ZoneId.of("UTC"));
YearMonth yearMonth = YearMonth.parse("0216", formatter);
System.out.println(yearMonth); // prints "2016-02"
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以将其转换YearMonth为a LocalDate,将其调整为该月的第一天,例如:
LocalDate localDate = yearMonth.atDay(1);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1485 次 |
| 最近记录: |