Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare dates with different timezones in moment.js

My server's date format is in UTC. I am running my node server in UTC format. I wanna check whether the current time is greater than 8AM in Indian timezone i.e +5.30 and should send a mail. How can I identify this using moment.js

like image 832
espeirasbora Avatar asked Jan 10 '16 15:01

espeirasbora


2 Answers

Using moment-timezone:

if (moment.tz("08:00","HH:mm","Asia/Kolkata").isBefore()) {
  // ...
}

Or, since India does not use daylight saving time, you actually don't need moment-timezone. You just need to specify the fixed offset correctly. Other zones that use DST or have other base-offset transitions to consider will indeed need moment-timezone.

if (moment.parseZone("08:00+05:30","HH:mmZ").isBefore()) {
  // ...
}

With both of the above, keep in mind that isBefore will default to the current time when there are no parameters. You could write it using moment().isAfter(...), instead, but it's slightly shorter the other way.

It doesn't matter whether you compare against UTC or local time because internally moment is tracking the instantaneous UTC-based value anyway.

like image 138
Matt Johnson-Pint Avatar answered Sep 23 '22 10:09

Matt Johnson-Pint


You can use isAfter and Moment Timezone:

// Get server date with moment, in the example serverTime = current UTC time
var serverDate = moment.utc();
// Get time in India with Moment Timezone
var indiaDate = moment.tz("Asia/Kolkata");
// Setting time to 8:00 AM (I'm supposing you need to compare with the current day)
indiaDate.hours(8).minutes(0).seconds(0);
if( serverDate.isAfter(indiaDate) ){
    // Server date is greater than 8 AM in India
    // Add here the code to send a mail
}
like image 29
VincenzoC Avatar answered Sep 24 '22 10:09

VincenzoC