Adding Days using Moment.JS

Simon Hume picture Simon Hume · Mar 31, 2015 · Viewed 31.5k times · Source

Having a few issues with simply adding a day to a few dates in an Appcelerator project using moment.js

All I want to do, is grab today's date and then display it in the DD format (01) and then get the next 6 days as well.

Here is what I'm trying:

var todayDate = moment();

var day1 = todayDate.format("DD");
var day2 = todayDate.add(1, 'days').format("DD");
var day3 = todayDate.add(2, 'days').format("DD");
var day4 = todayDate.add(3, 'days').format("DD");
var day5 = todayDate.add(4, 'days').format("DD");
var day6 = todayDate.add(5, 'days').format("DD");
var day7 = todayDate.add(6, 'days').format("DD");

But, the output I get is the following:

[INFO] :   31
[INFO] :   01
[INFO] :   03
[INFO] :   06
[INFO] :   10
[INFO] :   15
[INFO] :   21

It should read:

[INFO] :   31
[INFO] :   01
[INFO] :   02
[INFO] :   03
[INFO] :   04
[INFO] :   05
[INFO] :   06

What am I doing wrong?

Simon

Answer

Cyril N. picture Cyril N. · Mar 31, 2015

You add days to the same variable :

say todayDate is 31. First line, you add 1 day to todayDate, so it becomes 01. Then you add 2 days to todayDate (that is now "01") so it becomes 03 etc ...

Do this instead (depending on what you need of course) :

var day1 = moment().format("DD");
var day2 = moment().add(1, 'days').format("DD");
var day3 = moment().add(2, 'days').format("DD");
var day4 = moment().add(3, 'days').format("DD");
var day5 = moment().add(4, 'days').format("DD");
var day6 = moment().add(5, 'days').format("DD");
var day7 = moment().add(6, 'days').format("DD");

or just add 1 every time ;)

var todayDate = moment();

var day1 = todayDate.format("DD");
var day2 = todayDate.add(1, 'days').format("DD");
var day3 = todayDate.add(1, 'days').format("DD");
var day4 = todayDate.add(1, 'days').format("DD");
var day5 = todayDate.add(1, 'days').format("DD");
var day6 = todayDate.add(1, 'days').format("DD");
var day7 = todayDate.add(1, 'days').format("DD");