uber
uber

Reputation: 5073

How to work with Moment.js to return time in a 24-hours format when adding to it?

I get hours as strings in my app, e.g. "2230". I would like to be able to add minutes to it, so as to simulate the time that it will be after those minutes have been added to it, e.g.

//"2230" + "60"mins = "23:30"
//"2230" + "180"mins = "02:30" 

I read that Moment.js could be a solution to this, but I couldn't figure out:

  1. what the right way to format the hours initially is with moment("2230").format()

  2. how to add minutes to it

  3. how to make it behave like a 24-hour clock when adding to it

Upvotes: 1

Views: 2307

Answers (2)

Daviid
Daviid

Reputation: 238

First you have to split this string to get the hours and minutes from it.

const s= "2230"
const hour = s.substring(0,2);
const min = s.substring(2,4);

After that you can easily pass this hours and min to a moment.

const time = moment()
.set({"hour": hour, "minute": min})
.add(60, 'minutes')
.format("HH:mm");

the .set is to set the time (hours minutes)

the .add is to add the minutes you wanted to add

the .format is to format the output as you pleased, NOTE the capital "HH" means 24/h clock while "hh" means 12/h clock

Upvotes: 1

Nison M
Nison M

Reputation: 56

Moment is a great tool for doing this. It takes some syntax tricks to get it right, but I think this is what you're looking for:

moment("2230", "HH:mm")
  .add(60, "minutes")
  .format("HH:mm")

Feel free to play around with it here: https://codesandbox.io/s/proud-pine-lz0fs?file=/src/index.js

As you can see, as long as your time string is always 4 characters long, moment can extract the HH:mm format, then you can add minutes, and then format the final output to HH:mm again.

Here are 2 great resources:

https://techstream.org/Bits/Javascript/Javascript-Parse-time

https://flaviocopes.com/momentjs/

Hope that helps!

Upvotes: 3

Related Questions