Note that there are some explanatory texts on larger screens.

plurals
  1. POParsing a YYYY-MM-DD date strictly on Linux
    text
    copied!<p>POSIX defines a handy function, <code>strptime</code>, that can be used for parsing dates and times. Thus, theoretically, if I have a date of the format "YYYY-MM-DD", I should be able to use <code>strptime</code> to parse it like this:</p> <pre><code>char myDate[] = "2012-01-01"; struct tm result; char *end = strptime(myDate, "%Y-%m-%d", &amp;result); </code></pre> <p>… and get it back out in its canonical representation with:</p> <pre><code>if (end != NULL) { char outDate[11]; strftime(outDate, sizeof(outDate), "%Y-%m-%d", &amp;result); printf("%s\n", outDate); } else printf("Invalid date\n"); </code></pre> <p>On OS X and Linux, this prints out 2012-01-01. So far so good! However, let's say my input date is in the wrong format: 01-01-2012.</p> <p>If I run the above code again, on OS X, I get "Invalid date", which is expected. However, on Linux, I get 1-01-20 — January 20th, 1 (yes, year one).</p> <p>OS X follows the specifiers strictly, parsing a string as <code>%Y</code> <em>only</em> where a four-digit year exists. Linux takes a few liberties, though, and interprets two digits as a year — it doesn't even appear that it assumes it's 2001, it treats it as year 1!</p> <p>This can be worked around by changing my <code>if</code> statement to something like</p> <pre><code>if (end != NULL &amp;&amp; *end == '\0') </code></pre> <p>… but that seems hokey. Does anyone know if it's possible to make <code>strptime</code> on Linux behave more strictly, and fail for <code>%Y</code> if the input string does not have a four-digit 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