Search code examples
javascripttimezonemomentjsmariadbdst

Moment.js - Displaying historical data from selected range with regard of user timezone


I'm really confused about correctly displaying historical data:

What i have:

  • Database records stored in "YYYY-MM-DD HH:mm:ss" format and in UTC+0 (MariaDB - DateTime type)
  • Web application (using moment.js) which allows users to pick range between two dates (without time of day part)

What i need:

  • To fetch records from selected range but taking into account the time zone of the current user (so for example he chooses records only from 23 March: in DB i have a record from 22 March, but in user local timezone it was already 23 March, so if I'm thinking correctly, he needs to see that record too)
  • To handle the DST bullshit correctly
  • To display dates in result records in correct local time of user (as it was on that moment in past)

I'm hoping for some kind of guide that will explain to me what steps i have to take to achieve all of this. Thank you!


Solution

  • Define two variables in your client-side code:

    var startTime = moment().startOf('day').utc().format();
    var untilTime = moment().add(1, 'day').startOf('day').utc().format();
    

    You now have the range for your query in terms of UTC. Send them to the server via form post or whatever mechanism you have, then run the query.

    When you query, use a half-open range: recordTime >= startTime AND recordTime < untilTime

    When you bring the results back down to the client, you will have them in terms of UTC, so convert to local time like so:

    moment.utc(theData).local().format()
    

    Adjust input/output format as desired.