MomentJS returns an obscure date for the 1st month

I have a little problem with MomentJS returning a meaningless date. I am trying to set the date on the first of this month and year. I tried the following: -

var _year = 2015; var _month = 10; var _dateString = _year.toString() + '-' + _month.toString() + '-1'; var _date = moment(_dateString, 'YYYY-MM-D'); console.log('_date', _date.format('dddd, do MMMM YYYY')); 

This gives Thursday, 4th October 2015 as _date . Which does not exist. I tried using .set() and .date() , both give the same result: -

 var _date = moment(_dateString, 'YYYY-MM-D').set('date', 1); > Thursday, 4th October 2015 var _date = moment(_dateString, 'YYYY-MM-D').date(1); > Thursday, 4th October 2015 

So, I don’t see what I’m doing right now, can anyone suggest any suggestions or help?

Thank you very much.

+5
source share
1 answer

Your code is correct, except that you should use capital D not small D in do :

 console.log('_date', _date.format('dddd, Do MMMM YYYY')); 

The difference between do and do is:

  • do is the index of the day of the week, for example, if you check the calendar, you will find that October 1 is Thursday, the fourth day of the week when the index starts at 0, and if you change to October 2, and on Friday it will give you the 5th and the same for October 3 => 6th, and then a new week begins on Sunday, and then October 4 => 0th and starts again.

  • do is the index of the day in the month and what you expected the result to be, October 1 - October 1, October 2 => 2, etc.

Read more about docs for more information.

+5
source

Source: https://habr.com/ru/post/1231940/


All Articles