节点+ Mongodb + ISODate +时区问题 [英] Node + Mongodb + ISODate + Timezone issue

查看:400
本文介绍了节点+ Mongodb + ISODate +时区问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,我在Node js + mongodb中工作.

Hello I am working in node js + mongodb.

当我将数据插入集合时,数据将存储为默认的ISODate,例如ISODate("2016-06-17T13:00:21.665Z")

When I insert the data into collection the data is stored default ISODate eg. ISODate("2016-06-17T13:00:21.665Z")

我要插入日期字段应存储在UTC中.

I want to insert the date fields should be store in UTC.

它已经以UTC格式存储或需要更改代码中的任何内容?

Its already stored in UTC format or need to change anything in code ?

请任何人建议我.

我的代码:

var query = {};
query.created_by = 'admin';
query.created_on = new Date();
var collection = mongoUtil.list;
collection.insert(query, function(err, item) {
    if (!err && item) {
        console.log("success");
    } else {
        console.log("error");
    }

});

Mongo插入的数据:

Mongo inserted data:

{ "created_by" : "admin", "created_on" : ISODate("2016-06-17T13:00:21.665Z") }

我检查了引用- Mongo UTC引用 来自文档:

I checked the refference - Mongo UTC Refference From Document:

  1. Date()在mongo shell中以字符串形式返回当前日期.
  2. new Date()返回当前日期作为Date对象.蒙哥壳 使用ISODate帮助程序包装Date对象. ISODate在 UTC.
  1. Date() returns the current date as a string in the mongo shell.
  2. new Date() returns the current date as a Date object. The mongo shell wraps the Date object with the ISODate helper. The ISODate is in UTC.

推荐答案

是的,如abdulbarik的回答所述,MongoDB确实将日期保存为UTC.

Yes, as mentioned in abdulbarik's answer, MongoDB does save the Date in UTC.

日期对象:-

您可以使用getTimezoneOffset()方法获取UTC与本地时间之间的时差.

You can use getTimezoneOffset() method to get the difference between UTC and Local Time.

  var d = new Date()
  var n = d.getTimezoneOffset();

  console.log('date obj ==>' + d);
  console.log('time zone obj ==>' + n);

控制台日志:-

您可以看到时区obj的值为"-60".我在 GMT + 1 .

You can see the time zone obj has "-60". I am on GMT+1.

date obj ==>Mon Sep 12 2016 10:17:28 GMT+0100 (GMT Daylight Time)
time zone obj ==>-60

MongoDB将日期保留在UTC:-

我使用了对象"d"(即new Date())将日期保留在MongoDB中.尽管我在格林尼治标准时间+1,但日期存储在UTC.

I have used object "d" (i.e. new Date()) to persist the date in MongoDB. Though I am on GMT+1, the date is stored in UTC.

 "timestamp" : ISODate("2016-09-12T09:17:28.193Z"),

这篇关于节点+ Mongodb + ISODate +时区问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆