Without any additional libs, you can use the following utility methods to do the following:
var dateFromPicker = getDateFromPicker();
var dateUtc = localAsUtc(dateFromPicker);
var iso = dateUtc.toISOString();
function utcAsLocal(date) {
if (isNotValidDate(date)) {
return null;
}
return new Date(
date.getUTCFullYear(),
date.getUTCMonth(),
date.getUTCDate(),
date.getUTCHours(),
date.getUTCMinutes(),
date.getUTCSeconds(),
date.getUTCMilliseconds()
);
}
function localAsUtc(date) {
if (isNotValidDate(date)) {
return null;
}
return new Date(Date.UTC(
date.getFullYear(),
date.getMonth(),
date.getDate(),
date.getHours(),
date.getMinutes(),
date.getSeconds(),
date.getMilliseconds()
));
}
function isValidDate (date) {
return !isNotValidDate(date);
}
function isNotValidDate(date) {
return date == null || isNaN(date.getTime());
}
Here are a few examples that simulate time zones before and after UTC:
var date;
date = new Date("2016-12-06T00:00:00.000+0100");
date.toISOString();
date = localAsUtc(date);
date.toISOString();
date = new Date("2016-12-06T00:00:00.000-0100");
date.toISOString();
date = localAsUtc(date);
date.toISOString();
date = new Date("2016-12-06T00:00:00.000Z");
date.toISOString();
date = utcAsLocal(date);
date.toISOString();
date = new Date("2016-12-06T00:00:00.000Z");
date.toISOString();
date = utcAsLocal(date);
date.toISOString();
Run codeHide resultbut the answer would not be complete without mentioning moment.js , which simplifies date handling.
source
share