The Date type defaults to UTC format when json serialization in nodejs is solved

In nodejs, when json is serialized as Date type, it is converted to UTC format by default.

As shown below

The above is just an example. I will use a more specific example to show this situation. We often use Express components in the development of WEB projects.

We created a demo project with express

This is an express project, everyone is familiar with it, we are now going to provide an api interface to return some information

Return operator information, this is a normal interface, right?

Let's take a look, the time displayed in the interface log is 20:00 pm, but the JSON data returned by the interface is 12:00, a difference of 8 hours.

why?

The reason is that when JSON is serialized, the date type is converted to the time in UTC by default, and the UTC format has no time zone, or 0 time zone. The client automatically reconverts according to the local time zone.

JSON may be trying to avoid people making mistakes in time zones and causing time inconsistencies. But the problem is that the time must be processed, and it cannot be used without processing.

Can the output include the time zone by default, or can it be used directly without further processing?

The answer is yes. The following describes the processing method in express

In the www file in the bin directory, add the following code

 

function dateFormat(date, fmt) {
    if (null == date || undefined == date) return '';
    var o = {
        "M+": date.getMonth() + 1, //月份
        "d+": date.getDate(), //
        "h+": date.getHours(), //小时
        "m+": date.getMinutes(), //
        "s+": date.getSeconds(), //
        "S": date.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

Date.prototype.toJSON = function () { return dateFormat(this,'yyyy-MM-dd hh:mm:ss')}

 

As shown below

 

 The effect is as follows

 

In this way, the output contains the time zone and can be used directly without processing.

 

Summarize:

再次说明这并非是一个问题,开始的时候我们以为这个是Sequelize造成的,在github里也确实看到好多人在问为什么会这样?能不能解决呢,骂声一片,呵呵,我们就被误导了,英文不好嘛,所以看不太明白,以为是Sequelize搞的呢,甚至于搞到要修改Sequelize源码,觉得方案不完美。其实当时好像也有大牛说这不是Sequelize的问题,当时也没注意。后来第二天,又查了一下,好像不是Sequelize的问题,那是nodejs的问题?在网上查了一下,也有人说是Nodejs问题的。于是请教了一下鹅厂出来的同事,定位了一下,终于找到根源了。

原来是json序列化搞的鬼。

所以说遇到问题,要查百度没错,但也不能全信,一定要自己思考一下,必要时动手验证一下。

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324847226&siteId=291194637