Question

I have a date and a time value in the following formats "12-may-2014" and "16:05" respectively

I am trying to convert these two values to a moment object like so

var time = moment(originalDate + ', ' + orignalTime);

this seems to return a moment object so I do this

var newTime = moment(time).add('h', 3);
console.log(newTime);

this logs the expected time "19:05"

but if I do this

var newTime = moment(time).add('m', 30);
console.log(newTime);

instead of getting "16.30" i just get the original time "16.05"

edit: the selected answer solves my problem however if I replace

console.log(newTime.format("dddd, MMMM Do YYYY, h:mm:ss a")); 

with

console.log(newTime.format("HH:MM"));

I get the original problem. adding hours shows the correct result but adding minutes shows the original time

console.log(newTime.format("hh:mm"));

works as intended

Était-ce utile?

La solution

Seems to work fine for me. Are you sure you aren't confusing the 2 time variables?

Here is a working plunker.

JS:

var timevalue = "16:05";
var datevalue = "12-may-2014";
var time = moment(datevalue + ', ' + timevalue);

var newTime = moment(time).add('m', 30);
console.log(newTime.format("dddd, MMMM Do YYYY, h:mm:ss a"));

Autres conseils

For theirs, who can't understand what happening with moment.js objects

When you call momentValue.add('minute', amount) function it is return Moment object back, but it is not clone it is the same reference object with changed value. (between 3 and 7 lines)

So, if you don't want change original object you should use .clone function before apply changes. (between 9 and 14 lines)

moment using clone

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top