ND's
ND's

Reputation: 2215

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.

Upvotes: 7

Views: 17525

Answers (3)

mooga
mooga

Reputation: 3307

Just convert the Original time string to time then convert added time string to time then add them

  var time="18:15:00"; // Original Time
  var timeToadd = "00:15:00";  // Time to be added in min
  var timeToAddArr = timeToadd.split(":");             
  var ms = (60 * 60 * parseInt(timeToAddArr[0]) + 60 * (parseInt(timeToAddArr[1])) ) * 1000;
  
  var newTime =new Date('1970-01-01T' + time ).getTime() + ms
  var finalTime = new Date(newTime).toLocaleString('en-GB').slice(12 ,20)

  console.log(finalTime)

Upvotes: 0

NoLdman
NoLdman

Reputation: 56

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

Upvotes: 3

Dhaval Marthak
Dhaval Marthak

Reputation: 17366

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

Upvotes: 22

Related Questions