2

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.

Hommer Smith
  • 26,772
  • 56
  • 167
  • 296

3 Answers3

2

Use 2018Z in your year field:

var res = new Date('4/7/2018Z').toISOString();
console.log(res);
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62
1

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();

Expired Data
  • 668
  • 4
  • 12
-1

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));
RobG
  • 142,382
  • 31
  • 172
  • 209
  • Rob, thanks. What do you think of this as a solution: `var timezoneOffset = new Date().getTimezoneOffset() * 60000; new Date(new Date('4/7/2018') - timezoneOffset).toISOString()` – Hommer Smith Apr 30 '18 at 14:07
  • @HommerSmith—it's still using the built-in parser with an unsupported (by ECMA-262) format. – RobG Apr 30 '18 at 21:17