Prachi g
Prachi g

Reputation: 839

Using moment to manipulate date and time

I get the previous day using moment as follows:

var start_time = moment().tz("America/Los_Angeles").subtract(1, 'day').format('YYYY/MM/DD-00:00:00');

This outputs the following:

2015/01/29-00:00:00

Now I want to the following using start_time:

2015/01/29-01:00:00
2015/01/29-02:00:00
2015/01/29-03:00:00
2015/01/29-04:00:00
2015/01/29-05:00:00

I tried doing it the following way:

for(var i = 0; i<6; i++){
    console.log(moment(start_time,"YYYY/MM/DD-HH:mm:ss").add(1,'hour'));
}

But this is not working. How do I go about this?

Upvotes: 2

Views: 276

Answers (1)

DanielST
DanielST

Reputation: 14163

You almost had it.

for(var i = 0; i<6; i++){ //make sure to actually use i!
    console.log( //expects a string
        moment(start_time,"YYYY/MM/DD-HH:mm:ss") //this works
        .add(1,'hour') //this will return a moment object, not a string
    );
}

So just change it to

for(var i = 0; i<6; i++){
    console.log(
        moment(start_time,"YYYY/MM/DD-HH:mm:ss")
        .add(i,'hour') //changed to i
        .format('YYYY/MM/DD-HH:mm:ss') //make it a string
    );
}
// Prints
// 2015/01/29-00:00:00
// 2015/01/29-01:00:00
// 2015/01/29-02:00:00
// 2015/01/29-03:00:00
// 2015/01/29-04:00:00
// 2015/01/29-05:00:00

Upvotes: 1

Related Questions