Adding Days using Moment.JS
Asked Answered
C

2

16

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

Cohbath answered 31/3, 2015 at 13:14 Comment(0)
D
30

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");
Disturbing answered 31/3, 2015 at 13:18 Comment(1)
No you're not, idiots are those who don't asks questions and believe they are doing nothing wrong ;)Disturbing
C
2

You refer to the same variable

You add N days to todayDate, so next add-method will add N days to the already increased value of todays date, which is no longer 'today'

Calicle answered 31/3, 2015 at 13:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.