Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add 15 minutes to string in javascript

var time="18:15:00"

I am getting time in 24 hour format like above string. i have to add 15 minutes to time how can i add. Without using substring().

var time is string not a date object. Search on google but not get it.

like image 742
John Avatar asked Jul 03 '13 11:07

John


2 Answers

You can do like this:

 function addMinutes(time, minsToAdd) {
  function D(J){ return (J<10? '0':'') + J;};
  var piece = time.split(':');
  var mins = piece[0]*60 + +piece[1] + +minsToAdd;

  return D(mins%(24*60)/60 | 0) + ':' + D(mins%60);  
}  

addMinutes('18:15:00', '20');  // '18:35'

DEMO Plunker

like image 151
Dhaval Marthak Avatar answered Oct 22 '22 06:10

Dhaval Marthak


Dhavals answer is very nice, but I prefer simple & single-line code.
Therefore, I'd use following:

var minsToAdd = 15;
var time = "15:57";
var newTime = new Date(new Date("1970/01/01 " + time).getTime() + minsToAdd * 60000).toLocaleTimeString('en-UK', { hour: '2-digit', minute: '2-digit', hour12: false });

(If you need the seconds, just add second: '2-digit' to the formatting options.)

Further Information: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleTimeString

like image 2
NoLdman Avatar answered Oct 22 '22 04:10

NoLdman