user123_456
user123_456

Reputation: 5805

How to determine how many minutes has passed in javascript

I have variable which I populate from JSON formated data. Something like: var time=my_data[data.results[i].id].time; This gives me time from database in this format : 2012-06-19 15:48:18.140

How can save in some other variable value for example active if the time between a value that I get from database and time which is present(now) is less then 5 min and inactive if it is more then 5 min passed

Thank you

Upvotes: 5

Views: 5951

Answers (2)

Tamil
Tamil

Reputation: 5358

See the DOC for javascript Date

Date Constructor accepts a date string. I tried yours in chrome console it works fine. Then you can use getTime to get number of milliseconds since January 1, 1970

Finally

var past = new Date(yourTimeString).getTime();
var fiveMin = 1000 * 60 * 5; 
var isPast = (new Date().getTime() - past < fiveMin)?false:true;

Upvotes: 8

Romain Valeri
Romain Valeri

Reputation: 21938

var fiveMinutes = 1000 * 60 * 5;
var otherVariable = ((new Date().getTime() - time) < fiveMinutes) ? "active": "inactive";

But I'm unsure of the type you get from your JSON, so you might need to use this variant instead :

var fiveMinutes = 1000 * 60 * 5;
var otherVariable = ((new Date().getTime() - new Date(time).getTime()) < fiveMinutes) ? "active": "inactive";

Upvotes: 2

Related Questions