0

This code compares 2 time - present time and a deadline time.

// Get current date/time
var now = new Date(); 

// Set up deadline date/time
var deadline = new Date(); //deadline is 1830hrs;
deadline.setHours(18);
deadline.setMinutes(30);

// Check if the current time is after the deadline
if( now > deadline ) {
    console.log('after deadline');
}
else {
    console.log('before deadline');
}

It works on my local machine where now and deadline are in the same timezone. What if the code is run on a server where the now timezone can be different from the deadline timezone to be compared? How to handle the situation when now can be any timezone and deadline is in, say, the Asia/HongKong timezone?

EDIT: Is there some way to specify the timezone when creating deadline? I think this is a possible solution.

guagay_wk
  • 26,337
  • 54
  • 186
  • 295

3 Answers3

1

deadline and now are always in the same timezone because you new Date() there.

Tuan Anh Tran
  • 6,807
  • 6
  • 37
  • 54
  • Wait. Something does not sound right. Suppose the `deadline` which I set is meant to be in Asia timezone. But `now` is in U.S timezone. The timing outcome will not be desired. – guagay_wk Nov 09 '15 at 10:05
  • 1
    You can use `moment-timezone` to compare, given that you know the timezone of both dates. Otherwise, it's impossible to compare. – Tuan Anh Tran Nov 09 '15 at 10:06
1

As you creating both time in JS which the client side there will be no such case. because both time will read time from the same client.

But if in any case any of the time comes from server (in form of string of course )which located in another time zone and client is in another time zone then there is a possibility to this case happen.

Now you approach will be to convert both date to a specific time zone (any). Then make the comparison.

You can use This Library to convert time zone in JS.
And take help from This Thread.

Community
  • 1
  • 1
Saif
  • 6,804
  • 8
  • 40
  • 61
0

You are missing the information in what timezone the client is. This is partially solvable by just comparing it with the times form all the timezones.

In my example I will use moment.js because it is a nice library with a lot of features just for timezones.

You can use this code to find matching timezones, but sometimes they have different rules about DST and such so they will divert over the year.

However if that's fine you can now use moment.js to specify the timezone of deadline and calculate how much time you have left.

Community
  • 1
  • 1
online Thomas
  • 8,864
  • 6
  • 44
  • 85