amanpurohit amanpurohit - 5 months ago 29
Javascript Question

Conflicting dates in mongoose and express.js

The problem occurs when I declare my schema with type Date rather than String.

Case 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.

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.

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.

Answer

When you are saving dates to a mongo database, you can simply save a javascript Date object regardless of timezone. (Using the Date type as in case 2.) Then you would use moment to display the date in whatever timezone you require.

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);
});