繁体   English   中英

当本周的第一天在上一年时,如何严格解析只有年和周数的日期?

[英]How to strictly parse a date with only a year and a week number when the first day of this week is in the previous year?

我的目标是进行严格的解析(例如,禁止像“98/99”这样的日期)。 但是,以下代码会引发java.text.ParseException并显示消息Unparseable date: "98/01"

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

这确实是 1998 年的第一周,从星期四开始。 但是,一周的解析总是返回本周第一天的日期。 在这种情况下,它将是12/29/1997 这就是引发异常的原因。

似乎这个问题来自GregorianCalendar class ,更具体地说来自computeTime()方法,该方法检查原始字段是否与解析不宽松时外部设置的字段匹配:

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, 0, fields, 0, fields.length);
      throw new IllegalArgumentException(getFieldName(field));
    }
  }
}

这是一个错误吗? 我认为解析1998/01确实应该返回12/29/1997并且不会引发任何异常。 但是,您是否知道如何使解析返回01/01/1998 (这将是指定年份的一周的第一天)?

我认为这应该对你有用(你需要图书馆 joda 时间):

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();
}

您可以使用星期四作为参考,减去 3 天来计算星期一的日期。 ISO 8601 对第 1 周的定义是星期四发生的第一周。 这将消除补偿代码。 下面的代码将找到一周中的星期一,即使星期一是“上一个”年份。

String yearWeek = "201301";
DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyywwEEE").withLocale(Locale.US);
DateTime mondayInWeek= fmt.parseDateTime(yearWeek + "Thu").minusDays(3);// ISO 8601 def of week 1 is first week where Thursday occurs
System.out.println(mondayInWeek);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM