input – 15:30
output – 17:10
I try to do this:
time = '15:30' moment(time) .add(40, 'minutes') .add(2, 'hours') .format('HH:mm')
but it doesn’t work, moment says “invalid date”
Advertisement
Answer
First of all you need to parse the string data, we know we’re using a valid hour.
const time = '15:30' // Valid date const time = '252:10' // Invalid date
You can use a second parameter in the moment function, something like this:
moment(time, "HH:mm");
You simply need to know what format to convert your string to, read more about that in this documentation link.
Then, you can occupy the different builders to get the expected result.
moment(time, "HH:mm") // Parse the string .add(40, 'minutes') // Add 40 minutes .add(2, 'hours') // Add 2 hours .format('HH:mm') // Format to specified format
And finally you will get your date time parsed.
Here is a working version of this:
const time = '15:30' const date = moment(time, "HH:mm").toDate(); const parsedDate = moment(date) .add(40, 'minutes') .add(2, 'hours') .format('HH:mm') console.log(parsedDate);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js"></script>