java - 将字符串解析为本地日期不使用所需的世纪

标签 java date java-time 2-digit-year

我正在使用这个 DateTimeFormatter:

DateTimeFormatter.ofPattern("ddMMYY")

我想解析字符串 150790,但我得到了这个错误:

Unable to obtain LocalDate from TemporalAccessor: {DayOfMonth=15, MonthOfYear=7, WeekBasedYear[WeekFields[MONDAY,4]]=2090},ISO of type java.time.format.Parsed

显然,我想获得以下 TemporalAccessor:

{DayOfMonth=15, MonthOfYear=7, WeekBasedYear=1990}

你知道为什么我得到的是 2090 年而不是 1990 年吗?

谢谢你的帮助

最佳答案

因为这个问题真的是关于新的 java.time -package 而不是 SimpleDateFormat我将引用以下 relevant section :

Year: The count of letters determines the minimum field width below which padding is used. If the count of letters is two, then a reduced two digit form is used. For printing, this outputs the rightmost two digits. For parsing, this will parse using the base value of 2000, resulting in a year within the range 2000 to 2099 inclusive.

我们看到 Java-8 默认使用 2000-2099 范围,不像 SimpleDateFormat相对于今天的 -80 年到 +20 年的范围。

如果你想配置它那么你必须使用appendValueReduced() .这是以一种不方便的方式设计的,但可能,请参见此处:

String s = "150790";

// old code with base range 2000-2099
DateTimeFormatter dtf1 = 
  new DateTimeFormatterBuilder().appendPattern("ddMMyy").toFormatter();
System.out.println(dtf1.parse(s)); // 2090-07-15

// improved code with base range 1935-2034
DateTimeFormatter dtf2 = 
  new DateTimeFormatterBuilder().appendPattern("ddMM")
  .appendValueReduced(
    ChronoField.YEAR, 2, 2, Year.now().getValue() - 80
  ).toFormatter();
System.out.println(dtf2.parse(s)); // 1990-07-15

顺便说一句,如果你真的想要基于周的年份,那么你必须使用 Y 而不是 y 或适当的字段 IsoFields.WEEK_BASED_YEAR .关于您没有任何其他与周相关的字段这一事实,我假设是正常的日历年,而不是基于周的日历年。

关于java - 将字符串解析为本地日期不使用所需的世纪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29490893/

相关文章:

java - ViewModel 问题显示 MV VM 架构中的数据库更改

java - 寻找wordnet中同义词集之间的距离

mysql - MYSQL中将日期转换为日期范围---如何处理日期中的间隙

java - 需要 Java 8 中的非预期公历年表(如 org.joda.time.chrono.GJChronology)

java - 使用Gson在java中将LocalDateTime序列化和反序列化为RFC 3339格式的JSON

java - 如何使用灰度像素值从 Bitmap 创建 ByteBuffer?

java - 使用 AES/RSA 在 Java 中加密和解密数据

php - 租车 - 如何检查两个日期之间是否有车可用?

java.util.date 时间与系统时间不同

java - 日历行为与 LocalDate 不兼容?