简体   繁体   English

mongoose和express.js中的日期冲突

[英]Conflicting dates in mongoose and express.js

The problem occurs when I declare my schema with type Date rather than String. 当我声明我的模式类型为Date而不是String时,会出现问题。

Case I: 案例I:

var MySchema = new Schema({
    created_at: {type: String, default: ''}
});

With this shema declaration I use moment.js moment-timezone module for declaring current time in Asia/Kolkata timezone. 通过这个shema声明,我使用moment.js moment-timezone模块来声明亚洲/加尔各答时区的当前时间。

var tmoment = require('moment-timezone');
var currentTime = tmoment().tz('Asia/Kolkata').format('llll');

And I am able to get the correct time. 而且我能够得到正确的时间。

Case II: 案例二:

var MySchema = new Schema({
    created_at: {type: Date, default: ''}
});

With this shema declaration I use moment.js moment-timezone module for declaring current time in Asia/Kolkata timezone. 通过这个shema声明,我使用moment.js moment-timezone模块来声明亚洲/加尔各答时区的当前时间。

var tmoment = require('moment-timezone');
var currentTime = tmoment().tz('Asia/Kolkata').format('llll');

But now the time is not coming according to the timezone. 现在时间不是根据时区来了。 I even tried with the following declaration 我甚至尝试过以下声明

var tmoment = require('moment-timezone');
var currentTime = tmoment().tz('Asia/Kolkata').format();

But could not find a solution. 找不到解决方案。

When you are saving dates to a mongo database, you can simply save a javascript Date object regardless of timezone. 将日期保存到mongo数据库时,无论时区如何,都可以直接保存javascript Date对象。 (Using the Date type as in case 2.) Then you would use moment to display the date in whatever timezone you require. (使用Date类型,如果情况2)。然后,您将使用片刻在您需要的任何时区显示日期。

To save the object: 要保存对象:

var id = ...
var saveReq = new RequestModel({ _id: id, created_at: new Date() });
saveReq.save(function (err, result) {
  // ...
});

To read the object from the database, and then display the localized date string: 要从数据库中读取对象,然后显示本地化的日期字符串:

var tmoment = require('moment-timezone');
RequestModel.findOne({_id: id}, function (err, doc) {
  if(err) {} // ...
  var created = doc.created_at;
  var display = tmoment(created).tz('Asia/Kolkata').format('llll');
  console.log(display);
});

将服务器时区更改为您当地的时区。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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