Note that there are some explanatory texts on larger screens.

plurals
  1. POHow 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?
    text
    copied!<p>My goal is to have a strict parsing (and forbid dates like '98/99' for example). However, the following code raises a <code>java.text.ParseException</code> with the message <em>Unparseable date: "98/01"</em>:</p> <pre><code>SimpleDateFormat sdf = new SimpleDateFormat("yy/ww"); sdf.setLenient(false); sdf.parse("98/01"); </code></pre> <p>This is indeed for the <a href="http://www.timeanddate.com/calendar/monthly.html?year=1998&amp;month=1&amp;country=5" rel="nofollow">first week of 1998</a>, which starts on a Thursday. However, the parsing of a week always returns the date of the <strong>first day</strong> of this week. In that case, it would be <em>12/29/1997</em>. And this is why an exception is raised.</p> <p>It seems this problem comes from the <code>GregorianCalendar</code> class and more specifically from the <code>computeTime()</code> method which checks if the original fields match the fields externally set when the parsing is <strong>not lenient</strong>:</p> <pre><code>if (!isLenient()) { for (int field = 0; field &lt; 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)); } } } </code></pre> <p>Is this a bug? I think parsing <em>1998/01</em> should indeed return <em>12/29/1997</em> and not raise any exception. However, do you know how to make the parsing returns <em>01/01/1998</em> instead (which would be the first day of the week in the specified year)?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload