Search code examples
javascriptnode.jsmomentjshttpserver

moment.isoWeekday is not a function


I am using codesandbox and the same error keeps coming u: 502: bad gateway. Looking on the terminal it's apparently because moment.isoWeekday is not a function. Why is this?

I've looked on moment.js and the way I have put it in my code is apparently correct.

var http = require("http");
var moment = require("moment");
moment().format();

function getDates() {
  var start = moment.utc("1st Jan 2019");
  var end = moment.utc("31st December 2019");
  var dates = [];
  var current = start.clone();

  if (current !== moment.isoWeekday(1)) {
    current = moment().add(1, "w");
  }
  while (current.isBefore(end)) {
    current.clone.push(dates);
    current = moment.add(2, "w");
  }

  return dates;
}

http
  .createServer(function(req, res) {
    res.writeHead(200, { "Content-Type": "text/plain" });
    res.write("day,date", "\n");
    var dates = getDates();
    for (var i = 0; i < dates.length; i++) {
      res.write(moment.format("dddd, Do MMMM YYYY", dates[i]), "\n");
    }
    res.end();
  })
  .listen(8080);

I am doing a task of which I need to output dates. The isoWeekday is a part of the code which is supposed to check if the day is not Monday, then adds a week onto the variable so it sets to Monday the following week.


Solution

  • You have a couple of mistakes in your code:

    1. You forgot () after moment in moment.isoWeekday(1)
    2. The output of moment.utc("1st Jan 2019") is null because the format is not recognized by moment, moment.utc("1st Jan 2019", "Do MMM YYYY") should work as expected
    3. In order to push a clone of current onto the array dates you must do dates.push(current.clone()); instead of current.clone.push(dates);
    4. moment.format("dddd, Do MMMM YYYY", dates[i]) is incorrect, you must do dates[i].format("dddd, Do MMMM YYYY") instead

    Working example:

    function getDates() {
      var start = moment.utc("1st Jan 2019", "Do MMM YYYY");
      var end = moment.utc("31st December 2019", "Do MMM YYYY");
      var dates = [];
      var current = start.clone();
    
      if (current.isoWeekday() !== 1) {
        //current = current.add(1, "w");
        const nextMonday = 1 + current.isoWeekday() + (7 - current.isoWeekday());
        current.day(nextMonday);
      }
    
      while (current.isBefore(end)) {
        dates.push(current.clone());
        current = current.add(2, "w");
      }
    
      return dates;
    }
    
    console.log("day, date");
    var dates = getDates();
    for (var i = 0; i < dates.length; i++) {
      console.log(dates[i].format("dddd, Do MMMM YYYY"));
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>