Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

new Date() vs Date() and why does it return a different time (-2 hours)?

I have these 2 console logs, but they return different times (-2 hours off).

console.log(new Date()) // Date 2015-04-20T15:37:23.000Z
console.log(Date()) // "Mon Apr 20 2015 17:37:23 GMT+0200 (CEST)"

I know using Data() is the same as using the constructor and calling .toString().

However, i do need the Date() time and not the new Date() time. So why is it returning the wrong time and how can i reset it to output the correct one?

thx,

like image 277
kevinius Avatar asked Mar 17 '23 09:03

kevinius


1 Answers

So why is it returning the wrong time and how can i reset it to output the correct one?

Your first statement is calling console.log with a Date object. It appears that whatever browser/console plugin you're using chooses to display that Date object by using an ISO-8601 string in UTC. E.g., the format is chosen by the console implementation.

Your second statement is calling console.log with a string, so the format is chosen by the Date implementation. The specification makes no requirement on what that string format must be from JavaScript engine to JavaScript engine (yes, really*) other than that it must be in the local timezone.

Apparently, on your browser, the console implementation and the Date#toString implementation don't match up.

However, i do need the Date() time and not the new Date() time.

Those strings define the same moment in time (plus or minus a couple of microseconds); it's just that the strings have been prepared with different timezone settings.

If you need to log a string to the console in local time, use

console.log(String(new Date()));

...to reliably get the string from the Date object, not something generated by the console.


* Yup, the format you get from Date#toString is undefined and entirely up to the JavaScript implementation; the only requirement is that Date() and Date.parse() can both parse the string toString outputs and get back to the original date. (JavaScript didn't even have a standard date/time format until ES5, and it only applies to the toISOString method, not toString. And ES5 got it slightly wrong and it had to be amended in ES6, leading to the unfortunate situation at the moment where Chrome does one thing and Firefox does another when parsing strings in the new date/time format with no timezone on them.)

like image 81
T.J. Crowder Avatar answered Apr 12 '23 22:04

T.J. Crowder