In a project I am working on, I need to validate a date entered into an <input type="date">
With Safari 4/5 (on Mac OSX) the Javascript fails to parse dates of the format YYYY-MM-DD
, returning NaN
instead of the expected epoch timestamp.
I am using the following technique to validate the field just before the form is submitted:
//value = '2010-06-21' var stamp = Date.parse(value); if (isNaN(stamp)) { //notify user } else { value = new Date(stamp).format_mysql(); }
Where format_mysql()
is a prototype function that formats the date (correctly) into MySQL Date-Time format (YYYY-MM-DD).
Replacing the -
's with /
's (YYYY/MM/DD) yields a "correct" timestamp.
I should note that the field should accept any date format, not just YYYY-MM-DD, and that though I would like to, I cannot use libraries like Date.js
How can I fix this, or is there a better way to parse/validate a date?
If you navigate to System Preferences > Language & Region > Advanced > Dates you will see that you can change and customize the date settings to any format you choose independent of your language settings as Tom Gewecke stated.
The string format should be: YYYY-MM-DDTHH:mm:ss. sssZ , where: YYYY-MM-DD – is the date: year-month-day. The character "T" is used as the delimiter.
The Date. parse() method parses a string representation of a date, and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC or NaN if the string is unrecognized or, in some cases, contains illegal date values (e.g. 2015-02-31). Only the ISO 8601 format ( YYYY-MM-DDTHH:mm:ss.
The behavior of the Date.parse
method is implementation dependent, on ECMAScript 5, this method can parse ISO8601 formatted dates, but I would recommend you to make the parsing manually.
Some time ago I've made a simple function, that can handle a format specifier argument:
function parseDate(input, format) { format = format || 'yyyy-mm-dd'; // default format var parts = input.match(/(\d+)/g), i = 0, fmt = {}; // extract date-part indexes from the format format.replace(/(yyyy|dd|mm)/g, function(part) { fmt[part] = i++; }); return new Date(parts[fmt['yyyy']], parts[fmt['mm']]-1, parts[fmt['dd']]); } parseDate('06.21.2010', 'mm.dd.yyyy'); parseDate('21.06.2010', 'dd.mm.yyyy'); parseDate('2010/06/21', 'yyyy/mm/dd'); parseDate('2010-06-21');
Also you could detect the ECMAScript 5 behavior to parse ISO formatted dates, you can check if the Date.prototype.toISOString
is available, e.g.:
if (typeof Date.prototype.toISOString == "function") { // ES5 ISO date parsing available }
Generally DD-MM-YYYY format is not support in safari.
value = 2010/06/21 ; //should work.
(or)
value = new Date('2010-06-21'.replace(/-/g, "/"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With