Java – when the first day of the week is in the previous year, how to strictly analyze a date with only one year and one week?

My goal is strict parsing (for example, banning dates like 98 / 99) However, the following code raises a Java text. Parseexception, which contains the message unparseable date: "98 / 01":

SimpleDateFormat sdf = new SimpleDateFormat("yy/ww");
sdf.setLenient(false);
sdf.parse("98/01");

This is indeed the first week of 1998, starting on Thursday However, a week's resolution always returns the date of the first day of the week In this case, it will be December 29, 1997 This is why exceptions occur

It seems that this problem comes from the gregoriancalendar class, more specifically from the computetime() method, which checks whether the original field matches the externally set field when the resolution is not loose:

if (!isLenient()) {
  for (int field = 0; field < FIELD_COUNT; field++) {
    if (!isExternallySet(field)) {
      continue;
    }

    if (originalFields[field] != internalGet(field)) {
      // Restore the original field values
      System.arraycopy(originalFields,fields,fields.length);
      throw new IllegalArgumentException(getFieldName(field));
    }
  }
}

Is this a bug? I think the analysis of 1998 / 01 will indeed go back to December 29, 1997 without any exception However, do you know how to return the resolution to 01 / 01 / 1998 (this will be the first day of the week of the specified year)?

Solution

I think it should suit you (when you need the Library):

public static Date parseYearWeek(String yearWeek) {
    DateTime dateTime = DateTimeFormat.forPattern("yy/ww").parseDateTime(yearWeek);

    if (dateTime.getWeekOfWeekyear() == 1 && dateTime.getMonthOfYear() == 12) {
        dateTime = DateTimeFormat.forPattern("yyyy/mm").parseDateTime((dateTime.getYear() + 1) + "/01");
    }

    return dateTime.toDate();
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>