skip to Main Content

I am trying to check if the date of the last time an element was clicked is equal to the current date. The current date is being created by the server and is 5 hours ahead of my local time, so at a certain time of day, the code stops working correctly because the program thinks it’s now the next day.

Here is the code that is causing issues on my server side:

      let todaysDate = new Date().toString().split(' ').splice(0, 4).join(' ')
      let todaysDateMs = new Date(todaysDate + ', 00:00:00').getTime()

      Promise.all([
         Habits.updateMany({}, {
            $set: {
               todaysDate,
               todaysDateMs
            }
         }),
         Habits.updateMany({ lastClicked: { $ne: todaysDate } }, {
            $set: {
               clicked: 'false'
            }
         }),

The date that is being stored inside todaysDate is in UTC time and is 5 hours ahead. When it compares lastClicked (which is sent along with a PUT request from the client side in their local time) to todaysDate, it is setting clicked to false incorrectly because of the discrepancy between the timezones.

I am wondering if I can tell the server to create a date in the users local time or any way that I can work around this issue so that the two dates are the same. I don’t want specific timestamps included, only the day, month and year.

3

Answers


  1. Generally, times on servers are done in UTC and only at the client is it converted to/from their time zone. This removes the need for the server to know anything about the client’s time zone.

    The client will need to send their time zone along with the lastClicked time. Then your server can read this time and adjust for time zone automatically. One example is to send the time in ISO 8601 format 2023-02-07T18:25:19-05:00 where the -05:00 indicates that this time is 5 hours behind UTC.

    Alternatively, the client can pre-convert the timestamp their sending to UTC. JavaScript provides ways to do this, as do libraries such as Luxon.

    Login or Signup to reply.
  2. Have you tried something like Moment.js? It makes dealing with things like this a lot easier. Check out their documentation or tutorals like this.

    Login or Signup to reply.
  3. Date values in MongoDB are stored as UTC time – always and only. You should never store date/time values as string, it’s a design flaw.

    I your case I suggest a 3rd party library like moment.js, Luxon or Day.js

    They provide functions like DateTime.now().setZone('America/New_York').startOf('day').toJSDate();

    With these functions it should be fairly easy to solve your requirements.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search