Malcolmf
Malcolmf

Reputation: 95

Javascript hours ahead or behind now

I am trying to calculate the number of hours between now and some time in the future or the past. If the date/time is in the future it will be a positive number , if in the past a negative number.

I have tried

    var hours_away = Math.abs(flight_date.getTime() - now.getTime()) / 3600000;
    hours_away = parseInt(hours_away);

However if the flight_date variable is before or after now.getTime() the number is always returned positive.

Can anyone help with a date diff example that produces the right positive or negative result?

Upvotes: 0

Views: 144

Answers (3)

Towkir
Towkir

Reputation: 4004

To achieve this, you need to get your flight hours in a valid string type, and then create a valid date object out of that string, then you can subtract flight time from the current time, if it's ahed of now, you will get a positive number.

Check the function bellow:

// try changing the flight_time to see if this works or not

var flight_time  = '2018-10-28T20:20:30Z'; // assuming this is the flight time;
// now make a valid date format out of the given flight time;
var flight_hour = new Date(flight_time);
console.log(flight_hour)
var current_hour = new Date();
console.log(current_hour);

// now do the subtraction;
function calculate_hours() {
  var difference = ((flight_hour - current_hour) / 3600000).toFixed(2);
  document.getElementById('now').innerHTML = flight_hour.getHours();
  document.getElementById('difference').innerHTML = difference;
  console.log(difference) ;
}

calculate_hours();
<p> Now: <span id='now'></span></p>
<p> Difference: <span id='difference'></span></p>

Upvotes: 0

Edward Chew
Edward Chew

Reputation: 504

You are using math.abs which return absolute number (positive)

Upvotes: 0

omri_saadon
omri_saadon

Reputation: 10631

Math.abs means absolute value.

Absolute value always return a positive number.

x = |-5| // x is actually 5.

You can read from MDN

The Math.abs() function returns the absolute value of a number

Upvotes: 1

Related Questions