moment().format("LTS") returns a string value in hh:mm:ss AM/PM format. When you create a moment object using a string that is not in standard format, you should pass the input format as second parameter to moment constructor.

For eg: Jan 1, 2017 in string 01012017 is not a standard representation. But if you need a moment object out of it, using moment("01012017") will give "Invalid Date" response when formatting. Instead, use moment("01012017","DDMMYYYY")

var d = moment("01012017")
d.toISOString() => "Invalid date"

var d = moment("01012017", "DDMMYYYY")
d.toISOString() => "2016-12-31T18:30:00.000Z"

In your code, when creating 'date' variable pass "hh:mm:ss A" as second parameter in the moment constructor as mentioned below .

   var date = moment(startdate, "hh:mm:ss A")
        .add(seconds, 'seconds')
        .add(minutes, 'minutes')
        .format('LTS');
Answer from Muralidharan on Stack Overflow
Top answer
1 of 5
39

moment().format("LTS") returns a string value in hh:mm:ss AM/PM format. When you create a moment object using a string that is not in standard format, you should pass the input format as second parameter to moment constructor.

For eg: Jan 1, 2017 in string 01012017 is not a standard representation. But if you need a moment object out of it, using moment("01012017") will give "Invalid Date" response when formatting. Instead, use moment("01012017","DDMMYYYY")

var d = moment("01012017")
d.toISOString() => "Invalid date"

var d = moment("01012017", "DDMMYYYY")
d.toISOString() => "2016-12-31T18:30:00.000Z"

In your code, when creating 'date' variable pass "hh:mm:ss A" as second parameter in the moment constructor as mentioned below .

   var date = moment(startdate, "hh:mm:ss A")
        .add(seconds, 'seconds')
        .add(minutes, 'minutes')
        .format('LTS');
2 of 5
10

Moment has really good documentation. I would check it out: http://momentjs.com/docs/

But to address your question more directly, you could do something like:

var secondsToMinutes = '3:20';
var seconds = secondsToMinutes.split(':')[1];
var minutes = secondsToMinutes.split(':')[0];

var momentInTime = moment(...)
                   .add(seconds,'seconds')
                   .add(minutes,'minutes')
                   .format('LT');

You should use the actual handlers to the best of your ability. There are some cool things you can do with durations now, but this is more succinct.

Edit:

As mentioned in a different answer:

 moment('2:00:00 PM', 'h:mm:ss A')

Is necessary if you're handling that format. Regardless - adding/subtracting minutes/hours to a moment object is trivial. Passing invalid strings to a moment object is a different issue in-and-of itself. ;)

🌐
Readthedocs
momentjscom.readthedocs.io › en › latest › moment › 03-manipulating › 01-add
Add - momentjs.com
var m = moment(new Date(2011, 2, 12, 5, 0, 0)); // the day before DST in the US m.hours(); // 5 m.add(1, 'days').hours(); // 5 · If you are adding hours, minutes, seconds, or milliseconds, the assumption is that you want precision to the hour, and will result in a different hour.
🌐
Postman
community.postman.com › help hub
How to add minutes to moment js while looping - Help Hub - Postman Community
January 17, 2020 - So, I’m trying to add 15 minutes on each loop that I run. let startDatesHours = moment("1200", "hmm").format("HH:mm:ss") Now, for each run I want to add 15 minutes , so it would be 12:15 , 12:30 and so on… However, I’…
🌐
Moment.js
momentjs.com › guides
Moment.js | Guides
Warnings and Errors JS Date Construction Define Locale Override Parent Locale Undefined Locale Not Found Add/Subtract Min/Max Zone ... The guides area is designed to help developers learn to better interact with the date and time problem domain, and the Moment.js library.
Top answer
1 of 3
351

I think you missed a key point in the documentation for .add()

Mutates the original moment by adding time.

You appear to be treating it as a function that returns the immutable result. Easy mistake to make. :)

If you use the return value, it is the same actual object as the one you started with. It's just returned as a convenience for method chaining.

You can work around this behavior by cloning the moment, as described here.

Also, you cannot just use == to test. You could format each moment to the same output and compare those, or you could just use the .isSame() method.

Your code is now:

var timestring1 = "2013-05-09T00:00:00Z";
var timestring2 = "2013-05-09T02:00:00Z";
var startdate = moment(timestring1);
var expected_enddate = moment(timestring2);
var returned_endate = moment(startdate).add(2, 'hours');  // see the cloning?
returned_endate.isSame(expected_enddate)  // true
2 of 3
60

I am working on an application in which we track live route. Passenger wants to show current position of driver and the expected arrival time to reach at his/her location. So I need to add some duration into current time.

So I found the below mentioned way to do the same. We can add any duration(hour,minutes and seconds) in our current time by moment:

var travelTime = moment().add(642, 'seconds').format('hh:mm A');// it will add 642 seconds in the current time and will give time in 03:35 PM format

var travelTime = moment().add(11, 'minutes').format('hh:mm A');// it will add 11 mins in the current time and will give time in 03:35 PM format; can use m or minutes 

var travelTime = moment().add(2, 'hours').format('hh:mm A');// it will add 2 hours in the current time and will give time in 03:35 PM format

It fulfills my requirement. May be it can help you.

🌐
GitHub
github.com › moment › momentjs.com › blob › master › docs › moment › 03-manipulating › 01-add.md
momentjs.com/docs/moment/03-manipulating/01-add.md at master · moment/momentjs.com
moment().add(7, 'd'); Key · Shorthand · years · y · quarters · Q · months · M · weeks · w · days · d · hours · h · minutes · m · seconds · s · milliseconds · ms · If you want to add multiple different keys at the same time, you can pass them in as an object literal.
Author   moment
🌐
GeeksforGeeks
geeksforgeeks.org › node.js › moment-js-moment-duration-add-method
Moment.js moment.duration().add() Method - GeeksforGeeks
June 18, 2022 - The moment().duration().add() method is used to add a given time to the duration. The time to be added can be another Duration object, value in milliseconds, or a representation of the time using a string and numerical value.
Find elsewhere
🌐
Jscrambler
jscrambler.com › blog › a-moment-js-in-time
A Moment.js In Time
Moment.js lets you format your desired time in almost any pattern through its method of chaining. This allows you to do crazy things like the following: moment().add(7, 'days').subtract(2, 'months').year(2009).hours(3).minutes(6).seconds(9)...
🌐
Tabnine
tabnine.com › home page › code › javascript › moment
moment.Moment.add JavaScript and Node.js code examples | Tabnine
getNextTimeOfDayDate (trigger) { if (!trigger || trigger.type !== 'time-of-day' || !Number.isInteger(trigger.time)) { throw new Error('A valid time-of-day trigger must be provided.'); } const date = moment().utc(), getNextDate = (_date) => _date.startOf('day').add(trigger.time, 'minutes').startOf('minute'); let next_date = getNextDate(date); if (next_date.isSameOrBefore(new Date())) { next_date = getNextDate(date.add(1, 'day')); } return next_date; }
🌐
Logiforms
help.logiforms.com › hc › en-us › articles › 360045139171-Calculating-Time-adding-days-and-hours-to-find-durations-and-more-with-Moment
Calculating Time, adding days and hours to find durations and more with Moment – Logiforms Help Center
We now have a moment object "myMoment" ... a complete list of options see the moment.js docs. In this example, we have two fields, one named "StartTime" and the other named "EndTime". We calculate the time between the two fields on minutes and output it to the field "Outp...
🌐
GeeksforGeeks
geeksforgeeks.org › moment-js-moment-add-method
Moment.js moment().add() Method | GeeksforGeeks
July 26, 2022 - ... const moment = require('moment'); let momentA = moment(); console.log( "Current MomentA is:", momentA.toString() ); momentA.add(10, 'hours'); console.log( "Current MomentA is:", momentA.toString() ); momentA.add(45, 'minutes'); console.log( ...
🌐
ItSolutionstuff
itsolutionstuff.com › post › jquery-moment-add-minutes-to-datetime-exampleexample.html
JQuery Moment Add Minutes to Datetime Example - ItSolutionstuff.com
December 31, 2020 - Here, i will give you simple example of jquery moment js add() method for add minutes to date and jquery moment js subtract() method for subtract minutes from date.
🌐
GitHub
github.com › moment › moment › issues › 4838
Add minutes over day light saving · Issue #4838 · moment/moment
July 23, 2018 - When you add minutes to a moment ... 1540676700000 (ms) minutesAdd: 420 (minutes) Code used: var obj = moment(initalTime); obj .minutes(obj .minutes() + minutesAdd); ... js output: Mon Oct 29 2018 09:33:16 GMT+0100 ...
Author   FSondermann
🌐
TutorialsPoint
tutorialspoint.com › home › momentjs › moment.js add method
Moment.js Add Method
October 22, 2018 - Learn how to use the add method in Moment.js to manipulate dates and times effectively.
🌐
Postman
community.postman.com › help hub
How to add minutes to moment js while looping - #2 by john-paul - Help Hub - Postman Community
May 30, 2019 - Here’s how I just did it: if(!pm.variables.has('time')){ pm.variables.set('time',moment()); } var time = moment(pm.variables.get('time')); console.log('Time: ' + time.format()); time.add(15,'minutes'); console.log('Time + 15: ' + time.format()); ...
Top answer
1 of 2
3

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>

2 of 2
0

Adding 2 hours and 30 minutes to 15:30h will get you 18:10h - also without using moments.js:

const time=new Date(2022,1,1,15,30); // define initial datetime object
time.setHours(time.getHours()+2);
time.setMinutes(time.getMinutes()+40);
console.log(time.toTimeString().slice(0,5));

Another way of solving the problem, involving a Date.prototype definition could be:

Date.prototype.add=function(n,unit){ this"set"+unit+n); return this; }

console.log(new Date(2022,1,1,15,30)
                 .add(2,"Hours")
                 .add(40,"Minutes")
                 .toTimeString()
                 .slice(0,5) );

Before the protest comes in from all sides: Yes, I get it: extending the prototype of a built in class is not considered good programming style. The above example should therefore be seen as a demonstration of how the prototype function mechanism works in JavaScript and should probably not be incorporated in real projects.

🌐
Devhints
devhints.io › javascript libraries › moment.js cheatsheet
Moment.js cheatsheet
The one-page guide to Moment.js: usage, examples, links, snippets, and more.