When I do this:
new Date('4/7/2018').toISOString();
I get: "2018-04-06T22:00:00.000Z"
How can I get an ISO string but without the date changing from 7 to 6? I basically want the same date, month and year.
When I do this:
new Date('4/7/2018').toISOString();
I get: "2018-04-06T22:00:00.000Z"
How can I get an ISO string but without the date changing from 7 to 6? I basically want the same date, month and year.
Use 2018Z
in your year field:
var res = new Date('4/7/2018Z').toISOString();
console.log(res);
I think this is to do with the locale of the machine (i.e you're on gmt+2 so 4/7/2018 at 00:00:00 is indeed 2018-04-06T22:00:00.000Z)
You could do new Date('4/7/2018 GMT').toISOString();
Date strings do not have a timezone. Using the built-in parser for any format other than the one specified in ECMA-262 (a limited subset of ISO 8601) is implementation dependent and should not be used, see Why does Date.parse give incorrect results?
A couple of options are to parse the string as UTC values and then use toISOString and remove the trailing Z, or you can just reformat the string, e.g.
var s = '4/7/2018';
// Parse string in m/d/y format and return
// in ISO 8601 format
function parseDMY(s) {
var b = s.split(/\D/);
return new Date(Date.UTC(b[2],b[0]-1,b[1])).toISOString().slice(0,19);
}
console.log(parseDMY(s));
function reformatDate(s) {
var b = s.split(/\D/);
function z(n){return (n<10?'0':'')+n};
return `${b[2]}-${z(b[0])}-${z(b[1])}T00:00:00`;
}
console.log(reformatDate(s));
But really, if you just have a date, it should be left as just a date, so:
var s = '4/7/2018';
// Assume date is M/D/Y
function reformatDate(s) {
var a = s.split(/\D/).map(n=>(n<10?'0':'')+n);
return a[2]+'-'+a[0]+'-'+a[1];
}
console.log(reformatDate(s));