Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I subtract hours from a HH:MM AM time string in Javascript?

What's the best way to subtract a few hours from a time string formatted as such:

8:32 AM

I thought about splitting the string at the colon but when subtracting 3 hours from, say, 1:00 AM I get -2:00 AM instead of the desired 10:00 PM.

like image 956
Danny Garcia Avatar asked Jun 15 '11 23:06

Danny Garcia


1 Answers

Most reliable method is to convert it into a JS date object, then do you math on that

var olddate = new Date(2011, 6, 15, 8, 32, 0, 0); // create a date of Jun 15/2011, 8:32:00am

var subbed = new Date(olddate - 3*60*60*1000); // subtract 3 hours

var newtime = subbed.getHours() + ':' + subbed.getMinutes(); 

the Date object accepts either year/month/day/hour/minute/second/milliseconds OR a unix-style timestamp of milliseconds-since-Jan-1-1970 for the constructor.

like image 157
Marc B Avatar answered Nov 15 '22 14:11

Marc B