shady87 February 2016

Angular function to check if time is within 45mins of given time and if now is after time

I'm new to 'angularJS' and having a hard time creating a function that will check if a give 'time' is less than 45 minutes from now and also if the time is in the past that is now is after time

function checkTime(time) {
    var date = new Date();
    var date1 = new Date((date.getMonth() + 1) + "/" + date.getDate() + "/" + date.getFullYear() + " " + time);
    var minutes = (date1.getTime() - date.getTime()) / (60 * 1000);
    return (minutes > 40 || (minutes < 0 && minutes > -1395));
}

This is what I have so far, it checks that time is not greater than 45 mins from now

Any guidance appreciated!

Answers


Pankaj Parkar February 2016

Try below.

var date = new Date();
var date1 = new Date((date.getMonth() + 1) + "/" + date.getDate() + "/" + date.getFullYear()+ " " + time);

var diff = date.getTime() - date1.getTime();
var minutes = diff.getMinutes();
return (minutes > 40 || (minutes < 0 && minutes > -1395));


cyan February 2016

Solution with momentjs.

Angular directive for moment.

Moment js docs.

First install moment through bower:

bower install angular-moment moment --save

Include moment in your app:

<script src="components/moment/moment.js"></script>
<script src="components/angular-moment/angular-moment.js"></script>

( If you are using grunt, run grunt serve and it will automatically add these scripts, since you are using --save during bower install )

Add module angularMoment to Your app.

var myapp = angular.module('myapp', ['angularMoment']);

Now you can use momentjs in your controllers. I suggest moment, because it's easier to operate on dates than with pure javascript.

Your problem is to find it one point in time is before or after now in a specified time ( 45 mins ). It seems to me that imagine you have circle with radius. Radius is 45 mins and now is in the middle of circle. Then everything inside this circle is fine and everything outside is wrong. enter image description here

You also want to know if something is in past, so is on a left side of a circle.

So lets assume that middle is algebraic 0.

n is circle radius. ( 45 mins )

If t is argument ( given time ), then to check if it is inside:

f(t) = n - t
if f(t) is between 0 and t then it belongs on a right side. 
if f(t) is between t and 2t then it belonds and in on left side ( past ). 

With this preparation, time to implement in momentjs:

function  

Post Status

Asked in February 2016
Viewed 2,527 times
Voted 14
Answered 2 times

Search




Leave an answer