Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MomentJS returns obscure date for 1st of month

I'm having a small problem with MomentJS returning a nonsense date. I am attempting to set the date to the first of a given month and year. I have 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 the _date. Which doesn't 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 can't see what I'm doing wrong now, can anyone offer any suggestions or help?

Many thanks.

like image 984
dooburt Avatar asked Sep 21 '15 10:09

dooburt


1 Answers

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

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

Difference between Do and do is:

  • do is the index of the day in the week, for example if you check the calender you will find 1st October is Thursday which is the 4th day of the week as the index start from 0 and if you changed to 2 October which is Friday it will give you 5th and same for 3 Oct => 6th and then the new week start from Sunday then 4 Oct => 0th and start over again.

  • Do is the index of the day in the month and that what you expected the result to be, 1th Oct is 1th, 2nd Oct => 2nd and so on.

Check the docs here for more info

like image 122
mohamed-ibrahim Avatar answered Sep 29 '22 07:09

mohamed-ibrahim