Amit Bhagat
Amit Bhagat

Reputation: 4300

NodeJS incorrect `console.log` Date value

NodeJS outputs incorrect Date value in console.log

Assuming: var todayDate = new Date();

Machine timezone: GMT+0530 / IST

Following are results:

#1

console.log ('Today date:', todayDate);

Output: 020-04-04T09:54:29.107Z

#2 console.log ('Today date as UTC:', todayDate.toUTCString());

Output: Today date as UTC: Sat, 04 Apr 2020 09:54:29 GMT

#3 console.log ('Today date as string:', todayDate.toString());

Output: Today date as string: Sat Apr 04 2020 15:24:29 GMT+0530 (India Standard Time)

I am getting Output#1 whereas expected output is #3.

The Chrome browser shows same result as #3 which I expected with NodeJS since it runs on Chrome engine.

Please explain why NodeJS not output in local date/time.

Upvotes: 1

Views: 884

Answers (2)

Sebastian
Sebastian

Reputation: 483

I can confirm that behaviour. In my case I was looping through unix dates from database:

    console.log(endunix); //epoch date
    console.log(endutc); // wrong date that will be fixed from unixdate
    let nowadatautc = new Date(endunix*1000);
    console.log(nowadatautc); // new date
let sql2 = "update schedule a set end_time_utc='"+nowadatautc+"' where a.`event_id` > 374 and a.`sport_id` = 5";

and I get:

1645328100
2022-02-20T03:05:00.000Z
2022-02-20T03:35:00.000Z
update schedule a set end_time_utc='Sun Feb 20 2022 04:35:00 GMT+0100 (czas środkowoeuropejski standardowy)' where a.`event_id` > 374 and a.`sport_id` = 5

Upvotes: 0

domondo
domondo

Reputation: 1036

Fundamentally the Date object is the same in both chrome and node. It contains the number of seconds elapsed since the UNIX epoch. However different platforms chose to display it differently. Node.js calls toISOString(), while Chorome calls toString() (toString() in Node.js will return the same as in Chrome).

Upvotes: 2

Related Questions