-2

I have the following code:

console.log(    
  new Date().toISOString()
)  

This returns: 2021-10-14T08:28:28.467Z In my opinion it should return: 2021-10-14T08:28:28.000Z. The difference is the 000Z. In all examples (documentation) I see that it returns 000Z. In my case it doesn't.

How to make sure I also get the 000Z?

mplungjan
  • 169,008
  • 28
  • 173
  • 236
nhatimme
  • 383
  • 3
  • 19
  • 1
    You get that with examples [like the one the MDN provides](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString#using_toisostring), because there a new Date object is created, that explicitly does not have any milliseconds. You are using just `new Date()`, which _will_ have them, unless your code happened to execute exactly when the milliseconds were zero, which has a chance of 1 in thousand to happen. – CBroe Oct 14 '21 at 08:36
  • Why exactly should it return `000Z`? JavaScript dates represent ***milliseconds*** since unix epoch. – Salman A Oct 14 '21 at 08:46

1 Answers1

0

If you set the date yourself, you do get the 0s default if not you get the hh,mm,ss,sss the time has at the time the statement executes –

You have to set the milliseconds if you want 000

Not sure why you would expect 000Z

const d = new Date()
d.setMilliseconds(0)
console.log(d.toISOString())
mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • I different documentation, they do not set the miliseconds. Why are those miliseconds being used? – nhatimme Oct 14 '21 at 08:38
  • Why would they not? [The documentation shows them](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString) what documentation do you have? [ECMA](https://262.ecma-international.org/5.1/#sec-15.9.1.15) – mplungjan Oct 14 '21 at 08:46
  • Check that documentation of your first link. I don't see any preset of the setMilliseconds. It does output 000Z. So no seconds. – nhatimme Oct 14 '21 at 09:50
  • @nhatimme no rocket science. The two examples on that page create a date object, and explicitly set it to `05 October 2011 14:48 UTC`. Notice that the input date does not contain any seconds and milliseconds. You should actually be asking why `(new Date).toISOString()` does not return `:00` seconds unlike those MDN examples. – Salman A Oct 14 '21 at 10:03
  • If you set the date yourself, you do get the 0s default if not you get the hh,mm,ss,sss the time has at the time the statement executes – mplungjan Oct 14 '21 at 10:05