0

I have this code:

var utc = moment.tz(1521221491000, "UTC");
var local = utc.clone().tz(moment.tz.guess());
console.log(moment([2018, 03, 15]).fromNow());
console.log('moment() piece by piece: ' + moment().get('year') + ' ' + moment().get('month') + ' ' + moment().get('date') + '. Data inside of momment:  ' + moment().format());
console.log(local.format("YYYY-MM-DD HH:MM:SS"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.21.0/moment.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.14/moment-timezone-with-data.js"></script>

In the line 3

console.log(moment([2018, 03, 15]).fromNow());

Suppose to say '1 day ago', at the moment to write this question is 16 of March 2018... And for some reason the response is

in a month...

Any idea why this error, the error is in the month var.

aasanchez
  • 179
  • 1
  • 16
  • 1
    Possible duplicate of [Getting wrong month in moment.js](https://stackoverflow.com/questions/20094812/getting-wrong-month-in-moment-js) – Asons Mar 16 '18 at 19:14

3 Answers3

1

Moment uses the same (annoying) date system as the JavaScript Date object, where January = 0, February = 1, etc. So 3 means April, which is a month from now.

kshetline
  • 12,547
  • 4
  • 37
  • 73
1

As indicated in moment's documentation, when parsing an array as the argument, moment mirrors the native javascript Date object's 0-based indexing for months. So 3 is, confusingly, April.

I personally find it's much easier to have moment parse pre-formatted string or objects, though your mileage may vary.

user3351605
  • 1,271
  • 3
  • 19
  • 30
-1

Like answered by Gnagy in this thread (https://stackoverflow.com/a/20094956/8733102),

According to the documentation, months are zero indexed. So January is 0 and December is 11.

C. Reinhold
  • 43
  • 1
  • 5
  • 1
    We don't post answer with a link to another answer, we vote/flag to close as a duplicate...and if you haven't privileges to do that, move on to question where a proper answer can be given. – Asons Mar 16 '18 at 19:11