Home > Blockchain >  Javascript - Why time in ISO8601 format shows in 2 different formats at console.log?
Javascript - Why time in ISO8601 format shows in 2 different formats at console.log?

Time:11-15

I have date in ISO8601 format, e.g. '2021-01-01T00:00:00.000Z'. I try console.log it as part of string and as variable - I get two different results:

2021-01-01T00:00:00.000Z - when I show it as variable

Fri Jan 01 2021 01:00:00 GMT 0100 (Central European Standard Time) - when I show it as part of string

How could I show date in ISO8601 format '2021-01-01T00:00:00.000Z' as part of string?

let date = new Date(2021, 0, (1   (1 - 1) * 7), 1);

console.log('Show as variable: ', date);
console.log(`Show as part of string: ${date}`);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

edited: set proper date format.

CodePudding user response:

My guess is that it depends on each runtime's implementation of console.log. The template literal (your second example) would do the interpolation of the template before passing the whole thing to console.log, hence it will be a string already when logging (and it would use the same value as date.toString()), whereas the first variant passes a string literal and then an object, which isn't necessarily a string as well (and it's up to the console to decide how to display it; think of how you usually have more convenient display options for arrays, objects and so on).

Chrome seems to not care and shows both variants the same, whereas Firefox shows the first one as a Date instance. Node's CLI kind of behaves like Firefox and shows them differently, but doesn't show that the type is Date.

CodePudding user response:

This is same as

let date = new Date(2021, 0, (1   (1 - 1) * 7), 1);

console.log('Show as variable: ', date.toJSON());
console.log('Show as part of string: ', date.toString());
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

console.log(date) uses toJSON method and ${date} uses toString method.

Is it clear?

  • Related