Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add minutes and hours to a time string using jquery

I want to add 30 minutes and then one hour to my variable which i already have my own date

var initialDate = '10:00';

So

if (some condition){
    // i add 30 minutes ->10:30
}elseif(another condition){
    // i add 1hour ->11:00
}

I tried this but doesn't work

var initialDate = '10:00';
var theAdd = new Date(initialDate);
var finalDate = theAdd.setMinutes(theAdd.getMinutes() + 30);
like image 960
prince Avatar asked Nov 30 '22 15:11

prince


2 Answers

If I understand you correctly, the following will help you.

You need to add momentjs dependency via script tag and you can Parse, validate, manipulate, and display dates in JavaScript.

You can find more documentation regarding this in momentjs website

console.log(moment.utc('10:00','hh:mm').add(1,'hour').format('hh:mm'));

console.log(moment.utc('10:00','hh:mm').add(30,'minutes').format('hh:mm'));
<script src="https://momentjs.com/downloads/moment-with-locales.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
like image 188
SAMUEL Avatar answered Dec 03 '22 04:12

SAMUEL


var theAdd = new Date();

// Set Hours, minutes, secons and miliseconds
theAdd.setHours(10, 00, 00, 000);

if (some condition) {
   // add 30 minutes --> 10:30
   theAdd.setMinutes(theAdd.getMinutes() + 30);
}
elseif (some condition) {
   // add 1 hour --> 11:00
   theAdd.setHours(theAdd.getHours() + 1);
}

Then you print the var theAdd to obtain the date and time.

To obtain just the time:

theAdd.getHours() + ":" + theAdd.getMinutes();
like image 36
Ju Oliveira Avatar answered Dec 03 '22 03:12

Ju Oliveira