moments JS - correct way to compare local time

Viewed 90

I'm trying to use moment.js to compare a date stored in the database (which is set to Europe/London timezone) against the current users time, taking into account their timezone.

I get a date string returned from the database and want to use the fromNow() function, as follows:

console.log(dbDate);
console.log(moment().format());
console.log(moment(dbDate).fromNow());

// DB stored time (Europe/London)
// 2017-09-26 06:56:26

// Current user time (timezone is Pacific Time / Los Angeles)
// 2017-09-25T23:59:03-07:00

// String output by fromNow() function, which should reflect the timezone difference but doesn't
// in 7 hours

I want the fromNow() string to take account the timezone difference and this should always be a time "ago" as opposed to in the future.

I'm probably missing something quite obvious with the library, so apologies in advance if this is very simple.

2 Answers
// get the current time so we know which offset to take
var now = moment.utc();
// get the zone offsets for this time, in minutes
var NewYork_tz_offset = moment.tz.zone("America/New_York").offset(now); 
var MY_DATE = moment(dbDate);
// calculate the difference in hours
console.log((NewYork_tz_offset - MY_DATE) / 60);

Does this help your cause?

You have to use moment timezone, you can parse dbDate specifying "Europe/London" timezone using moment.tz:

The moment.tz constructor takes all the same arguments as the moment constructor, but uses the last argument as a time zone identifier.

Then you can use moment diff and fromNow.

Here a live example:

var dbDate = "2017-09-26 06:56:26";
var now = moment();
var momDbDate = moment.tz(dbDate, "Europe/London");
var pacificTime = moment("2017-09-25T23:59:03-07:00");
console.log(dbDate);
console.log(moment().format());
console.log(momDbDate.fromNow());
console.log(momDbDate.diff(now, 'hours'));
console.log(momDbDate.diff(pacificTime, 'hours'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.13/moment-timezone-with-data-2012-2022.min.js"></script>

Related