const Jobs = new mongoose.Schema({
conditions: {
type: String,
required: true,
},
job_status: {
type: String,
default: "Running",
},
submit_time: {
type: Date,
default: Date.now,
},
});
This is the model i have written , i have a doubt like how to create this default time in ist or asia/kolkata timezone . Is it recommended to do the timezone thing in backend or have all the conversions in FE ?
3
Answers
you can use moment-timezone library to have the job done
here’s how to use it in your schema
When you are using the
Date
JavaScript object, the date is in UTC standard. It is calculated with the number of milliseconds elapsed since January 1, 1970, UTC 0 at midnight (the epoch). Depending of the methods used and your JavaScript environment, someDate
methods will display the date to the local timezone where your JavaScript process is running and some other methods will display it to the UTC 0 timezone.Date.now()
does not returns a date but a simple number. It returns the number of milliseconds in UTC 0. You can add to it the offset of your timezone if you wantDate.now() + (330 * 60000)
(IST is +5:30 so 330 minutes to convert in milliseconds), but this is not howDate
works.Date
should use the epoch date (UTC +0).my_date = new Date()
create an instance with theDate
constructor function. The internal number used is still the UTC +0, but your instance is aDate
object now. It gives you access to theDate
object with his methods to manipulate the date. If you callmy_date.toString()
you will get the date in the local timezone of the JavaScript process environment. If you callmy_date.toJSON()
you will get the UTC +0 date.In you case, you are trying to store a number inside a mongoose
Date
type. Most of the time, the practice is to usenew Date()
instead ofDate.now()
or to change your type fromDate
toNumber
. Then, you work with your date after retrieving it from the database to display it in the timezone you choose. You can do that in the back or in the front, your choice. You can manipulate the date with your own calculations or with a library which already do the calculations for you, most famous one is moment. Note that you are usingDate.now
as a property instead ofDate.now()
as a method. Note also that you can use timestamps with mongoose if you just need a creation time and an update time. Mongoose provide them because it is very common.OR
You can get details about Date object here : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date
According to the MongoDB spec, Date “represents the number of milliseconds since the Unix epoch (Jan 1, 1970).” This means that it does not store any time zone information anyway1. If you want, you can convert the timestamp into the Asia/Kolkota time zone after you read it back from the database1.
You can use the moment-timezone library to convert the timestamp to the Asia/Kolkata timezone
Here’s an example:
It is recommended to do the timezone conversion in the backend