anmml anmml - 4 months ago 11
Javascript Question

Add minutes to a hh: mm string

I want to add 30 minutes to this

9:00
string in JavaScript?

(Without using
Date
object)

Answer

If it's just a string, just use the logic.

var d = "9:00";
d = d.split(":");
var min = 30;
if (+d[1] + min >= 60) {
  d[1] = (+d[1] + min) - 60;
  d[1] = ("0" + d[1]).substr(-2);
  d[0]++;
} else {
  d[1] = (+d[1] + min);
}
console.log(d.join(":"));

var d = "9:45";
d = d.split(":");
var min = 30;
if (+d[1] + min >= 60) {
  d[1] = (+d[1] + min) - 60;
  d[1] = ("0" + d[1]).substr(-2);
  d[0]++;
} else {
  d[1] = (+d[1] + min);
}
console.log(d.join(":"));

The above one can be converted into a reusable function:

function addD(d, min) {
  d = d.split(":");
  if (+d[1] + min >= 60) {
    d[1] = (+d[1] + min) - 60;
    d[1] = ("0" + d[1]).substr(-2);
    d[0]++;
  } else {
    d[1] = (+d[1] + min);
  }
  return (d.join(":"));
}

console.log(addD("9:00", 30));
console.log(addD("9:15", 45));
console.log(addD("9:00", 75));
console.log(addD("9:30", 45));