I am trying to format a array of dates using moment.js
but I get an error stating
dayOfWeek.format is not a function
I am correctly imported
var startOfWeek = moment().startOf('isoWeek');
var endOfWeek = moment().endOf('isoWeek');
var days = [];
var day = startOfWeek;
while (day <= endOfWeek) {
days.push(day.toDate());
day = day.clone().add(1, 'd');
}
var week = days.map(function(dayOfWeek, i){
console.log(dayOfWeek);
dayOfWeek.format("dddd, DD-MM-YYYY")
});
Your code will fail because dayOfWeek
is not moment
object.
To check if your variable is moment
object use .isMoment
:
moment.isMoment(dayOfWeek)
.
To fix your problem simply replace
dayOfWeek.format("dddd, DD-MM-YYYY")
with
moment(dayOfWeek).format("dddd, DD-MM-YYYY")
You are also missing return
statement inside .map
function.
Working example:
var startOfWeek = moment().startOf('isoWeek');
var endOfWeek = moment().endOf('isoWeek');
var days = [];
var day = startOfWeek;
while (day <= endOfWeek) {
days.push(day.toDate());
day = day.clone().add(1, 'd');
}
var week = days.map(function(dayOfWeek, i){
return moment(dayOfWeek).format("dddd, DD-MM-YYYY")
});
console.log(week);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
moment().format()
function usage is not correct.
Current is:
dayOfWeek.format("dddd, DD-MM-YYYY")
Change to:
moment(dayOfWeek).format("dddd, DD-MM-YYYY")
Check here for more information: https://momentjs.com/docs/#/parsing/string-formats/
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