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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With