简体   繁体   中英

Moment.js Add a time in minutes to a time in hours:minutes

Consider the user inputs,

var firstTrainTime = 12:00 //input as **hours:minutes**
var frequency = 30 //input as any number (user could for instance 
enter 1345 minutes) of **minutes**

Both of these variables are input as strings.

I'm attempting to use Moment.js to produce the "next arrival" time of the train so that it outputs

var arrival = 12:30 //this will be in 24hr format ("HH:mm")

My code:

var a = moment(firstTrainTime, "HH:mm");
console.log("this is firstTrainTime " + a);

var b = moment(freq, "m");
console.log("this is freq " + b)

var nextArrival = a.from(b);
console.log("this is nextArrival " + nextArrival);

nextArrival = moment().format("HH:mm");
console.log("this is nextArrival " + nextArrival);

Var's a & b return moment objects - but, then when I run the "from" method on them it returns "12 hours from now" in console.

I'm coding this for a webapp using javascript/jquery.

Thanks so much! Any guidance appreciated.

var firstTrainTime = 12:00 //input as **hours:minutes**
var frequency = 30         //input as any number (user could for instance enter 1345 minutes) of **minutes**

moment(firstTrainTime, 'HH:mm').add(frequency, 'minutes').format("HH:mm")
//"12:30"

Documentation on #add() for moment: https://momentjs.com/docs/#/manipulating/add/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM