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: ''}
});
moment-timezone
var tmoment = require('moment-timezone');
var currentTime = tmoment().tz('Asia/Kolkata').format('llll');
var MySchema = new Schema({
created_at: {type: Date, default: ''}
});
moment-timezone
var tmoment = require('moment-timezone');
var currentTime = tmoment().tz('Asia/Kolkata').format('llll');
var tmoment = require('moment-timezone');
var currentTime = tmoment().tz('Asia/Kolkata').format();
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);
});