Moment js gives incorrect time

namko :

I am using moment.js in Nodejs to get the current date and time. The date part I am getting is correct but the time is off by 4 hours. For example time here in Michigan is 1:03 PM but moment is giving 6:00 PM

I am inserting this time in the database and to get the current time, I am doing:

moment()

Tobiah Rex :

Scalability Issues:

Let's first point out, you shouldn't be saving local time into your database. Your database should have as little bias as possible, i.e. should not be bound to the local timezone. Why? Well when you scale your solution and deploy to a cloud service like AWS, and you have to instantiate multiple servers in multiple hosted zones, that exist in various locations throughout the globe, your database will immediately be in a very bad situation, and be saving times in a non-deterministic fashion, thus giving you many future bugs to kill.

Solution:

Start by only saving UTC time into your database: moment.utc(). Then in the front end (assuming you have one), the user's browser has a localized timezone caked into it's runtime. Therefore, you have several options available for managing consumption by the user's application.

Solution Options

  1. In your front-end code, moment().format('hh:mm') will be the local timezone as set by the browser/phone/device whatever is consuming the DB data.

  2. If you give that same algo from 1, the DB utc time, moment(<time from db as UTC>).format('hh:mm') you'll only see the UTC time formatted.

  3. Now if you want the DB time (UTC) to be shown as a local time to your respective user, you can do moment(val).utcOffset('-0400').format('hh:mm')

The main takeaway, is you need to remove your server time-bias from the solution. Otherwise you'll have really bad issues moving forward. And you need to account for browser-time bias in your solution, if the time in your DB will be consumed by a user-facing application.

NOTE: .format() method has tons of configurations. I picked hh:mm simply for intuitive example sake. This should obviously be changed to fit your needs.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=31738&siteId=1