Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if time difference is less than 45 mins and run function - AngularJS

This is an easy thing to do in PHP with code like this;

if (strtotime($given_time) >= time()+300) echo "You are online";

But can't find anything on SO to do exactly this in javascript. I want to check if the difference between a given time and the current time is less than 45mins

For instance

$scope.given_time = "14:10:00"
$scope.current_time = new Date();

I'm only concerned with the time part. I need to extract time part from new Date(); and then compare.

Then this should be true

How can I achieve this with Javascript:

if ($scope.given_time - $scope.current_time < 45 minutes) {
   // do something
}
like image 359
moh_abk Avatar asked Dec 04 '15 14:12

moh_abk


1 Answers

Javascript uses unix timestamps in milliseconds, so it is similar to the output of strtotime (which uses seconds).

var date = new Date();

Then you'll need to do the calculation from milliseconds. (Minutes * 60 * 1000)

You can also use date.parse() to parse a string to milliseconds, just like strtotime() in PHP does to seconds.

In full:

var date = new Date();
var last = new Date('Previous Date'); // or a previous millisecond timestamp
if ( ( date - last ) > ( 45 * 60 * 1000 ) ) {
   // do something
}

You could use a static date to compare just time, this is exactly what strtotime does if you exclude the date:

var last = new Date('1/1/70 14:10:00');
var date = new Date('1/1/70 14:30:00');

However, this approach will fail if you're trying to compare time that cross over day boundaries.

like image 159
Devon Avatar answered Sep 19 '22 08:09

Devon