Reputation: 15730
I have large arrays of dates in the client, and I want to send them in a JSON string to the server without a timezone, that is, I just want to send 2015-04-01
(the client local date) instead of 2015-03-31T16:00:00.000Z
, which is the corresponding UTC date. The simplest way of achieving that seems to me to just override .toJSON
.
My initial idea was to use datetime.js such as:
function toJSON(dt) {
return datetime.strftime(dt, '%Y-%m-%d');
}
Date.prototype.toJSON = toJSON;
However, I don't know how to reference dt
(the instance's self) to accomplish that.
Yes, I am thinking in Python still...
Upvotes: 0
Views: 2485
Reputation: 147453
Maybe you need datetime.js for other things, but if you're just using if for this, you might consider a simple function (perhaps attached to Date.prototype or given a more meaningful name):
function toJSON(d) {
// Helper for padding
function pad(n, len) {
return ('000' + n).slice(-len);
}
// If not called on a Date instance, or timevalue is NaN, return undefined
if (isNaN(d) || Object.prototype.toString.call(d) != '[object Date]') return;
// Otherwise, return an ISO format local date string
return pad(d.getFullYear(), 4) + '-' +
pad(d.getMonth() + 1, 2) + '-' +
pad(d.getDate(), 2);
}
document.write(toJSON(new Date()));
Upvotes: 2
Reputation: 388416
Since toJSON is assigned as the prototype method, this
will refer to the date inside the method so
function toJSON() {
return datetime.strftime(this, '%Y-%m-%d');
}
Date.prototype.toJSON = toJSON;
Upvotes: 3