Store wrong timezone in default date and time

735 views Asked by At

I am trying to store default date and time using mongoose with the Node.JS but somehow, it is storing different time zone value in database. I'm using "MongoDB Atlas Database" as a DB server and also configured default time zone with reference to this. I have also tried this for change time zone and also tried "moment-timezone.js", But didn't get any luck.

I just want to store default date and time with Indian standard time format.

Following is my code for the schema.

const testSchema = new mongoose.Schema({
    from: String,
    to: String,
    amount: Number,
    message: {
        type: String, 
        default: ""
    },
    creationdate: { 
        type: Date, 
        default: Date.now
    }
});

Please help me with this issue. Show me the best way to solve this problem.

1

There are 1 answers

2
Matt On BEST ANSWER

MongoDB stores Date fields as a UTC timestamp in milliseconds since the Unix epoch, which is a 64bit integer (53bit in JS). This is also what Date.now() is. There is no timezone component to the data by design.

If you need a consistent timezone format for a Date object, add a virtual field that returns the required timezone adjusted string or object from the date.

const testSchema = new mongoose.Schema({
    creationdate: { 
        type: Date, 
        default: Date.now
    }
});
testSchema.virtual('formattedCreationDate').get(function() {
  return this.creationdate.toLocaleString(); // or day.js/luxon 
});

If you need a timezone other than the user or system supplied value, store the required TZ data in another field and use that timezone field in the virtual formatting.

The virtual will probably be easier if you use day.js or luxon.