1

I am trying to add my users timezone offset to my DB query, since the dates in my MongoDB database are saved in UTC by default. Basically, I'm trying to query by the users 'today'.

I have my users Timezone. For this example let's say it is 'America/New_York' which currently has a -04:00 offset.

In the backend I am making a query:

let presentHour  = new Date().getHours();    //current hour of the day
let presentDay   = new Date().getDate();     //current day of the month
let presentMonth = new Date().getMonth();    //current month of the year
let presentYear  = new Date().getFullYear(); //current Year

Mood.find({

userId: req.user._id, 

createdAt: {
  "$gte": new Date(presentYear, presentMonth, presentDay, presentHour, 0, 0, 0),
  "$lt": new Date(presentYear, presentMonth, presentDay+1, 23, 59, 59, 999)
  } ....

As you can notice, I am not accounting for the offset.

From moment.js I am getting the timezone offset value like this:

-04:00

What is the best way to account for this in my query?

Walter Monecke
  • 2,386
  • 1
  • 19
  • 52
  • See if this helps http://stackoverflow.com/questions/948532/how-do-you-convert-a-javascript-date-to-utc – s7vr May 11 '17 at 17:56
  • Thank you but this didnt really help me that much. – Walter Monecke May 11 '17 at 18:39
  • Can you expand a little bit more as what specifically you need help with ? Adding offset to Mongo query is not going to work b/c America/NewYork has DST – s7vr May 11 '17 at 18:40
  • Let's say that, the DST variations are taking care of. I would just like to adjust the query to account for the -04:00. Aka modify the presentHour variable to account for it. – Walter Monecke May 11 '17 at 18:47
  • I would a little hesitant to adjust `presentHour` directly by offset. May be you can take a step back and create a moment object with the users timezone and convert it to UTC for query. Something like http://stackoverflow.com/a/17995098/2683814 – s7vr May 11 '17 at 19:01
  • `new Date(presentYear, presentMonth, presentDay+1, 23, 59, 59, 999)` will create a date for (almost) midnight tomorrow night. – RobG May 11 '17 at 21:01

0 Answers0