Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't format using moment.js

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")
});
like image 849
Sam Avatar asked Jul 02 '18 13:07

Sam


2 Answers

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>
like image 122
loelsonk Avatar answered Sep 20 '22 05:09

loelsonk


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/

like image 22
Vikasdeep Singh Avatar answered Sep 20 '22 05:09

Vikasdeep Singh