Reliable cross browser method for setting and getting date datpicker

I have a datepicker that I get and set a date with (which is then serialized to JSON using json2.js using the following code:

$('#element').datepicker('getDate'); // returns 2012-03-19T00:00:00.000Z
$('#element').datepicker('setDate', value);

      

Unfortunately, however, this sets the date value in the datpicker in 30/08/2017

Firefox v11 (which is still wrong, I don't know where to get it from) and NaN/NaN/NaN

IE9.

I tried to change the second line like this:

$('#element').datepicker('setDate', new Date(value));

      

This works in Firefox, but I still get the same result in IE9.

Then I staggered a bit and started trying to use string manipulation to write and parse dates in some other format, hoping that I could reliably get a simple write / parse script to work, but that turned out to be a lot more code than I expected - combined with the fact that I need to take time zones into account (in some time zones I can get something like 2012-03-18T23:00:00.000Z

during 2012-03-20, i.e. the date component indicates the date of the previous one) my confidence is currently shaking how important it is that it works across time and across browsers.

Is there a reliable way to use JSON safely to load JSON from JSON?

  • I am only interested in the date component, not the time component
  • The date format itself doesn't matter as long as it uniquely identifies the date (for example, I would like to avoid 01/01/2012 due to the ambiguity between US and UK dates). It would be nice if it was human readable, but if it makes a difference between its work, then I would prefer it to work!
+3


source to share


1 answer


At the moment I have written some short JavaScript functions to emit and parse ISO8601 date-only date strings (for example 2012-03-20

), here they are:

/**
* Parses an ISO8601 date string
*/
function parseISODate(str) {
    var dateParts = str.split('-');
    var retVal = new Date;

    retVal.setUTCFullYear(Number(dateParts[0]));
    retVal.setUTCMonth(Number(dateParts[1]) - 1);
    retVal.setUTCDate(Number(dateParts[2]));

    return retVal;
}

/**
* Gets an ISO8601 date string
*/
function iSODateString(d) {
    function pad(n) {
        return n < 10 ? '0' + n : n;
    }
    return d.getUTCFullYear() + '-'
        + pad(d.getUTCMonth() + 1) + '-'
        + pad(d.getUTCDate());
}

      

In addition, I also need to adjust the date given to me with the date parser to UTC, since otherwise at certain time intervals I get yesterday's date:



var value = $('#element').datepicker('getDate');
value.setMinutes(value.getMinutes() - value.getTimezoneOffset());
return iSODateString(value); // gives me 2012-03-19

$('#element').datepicker('setDate', parseISODate(value));

      

Surprisingly, none of the following methods worked when trying to parse dates in the above format:

  • Standard IE9 Date.parse

  • js-iso860
  • Datejs
+1


source







All Articles