简体   繁体   中英

nodejs (new Date()).toJSON() returns a wrong time

I'm using the following code to get current date and time in nodejs.

var date = (new Date()).toJSON();

after converting to JSON, it returns a wrong time with a wrong timezone as below:

2018-01-03T11:16:38.773Z

but without toJSON() it returns the real time in correct timezone

Wed Jan 03 2018 14:47:12 GMT+0330 (Iran Standard Time)

The format is different because:

The toJSON method is a built-in member of the Date JavaScript object. It returns an ISO-formatted date string for the UTC time zone (denoted by the suffix Z).

What you can do:

You can override the toJSON method for the Date type, or define a toJSON method for other object types to achieve transformation of data for the specific object type before JSON serialization.

source

If you want the same result you could just use toString instead of toJSON:

var date = new Date().toString();
2018-01-03T11:17:12.000Z === Wed Jan 03 2018 14:47:12 GMT+0330 (Iran Standard Time)

The one on the left hand side is ISO timezone and one on the right is basically the browser timezone.

(new Date()).toJSON() converts into ISO timezone

So a simple way to convert to string is

var date = (new Date()).toString(); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM