无法使用moment.js格式化

时间:2018-07-02 13:01:03

标签: javascript web frontend momentjs

我正在尝试使用moment.js格式化日期数组,但出现错误提示

  

dayOfWeek.format不是函数

我已正确导入

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")
});

4 个答案:

答案 0 :(得分:1)

moment().format()函数用法不正确

当前为:

dayOfWeek.format("dddd, DD-MM-YYYY")

更改为:

moment(dayOfWeek).format("dddd, DD-MM-YYYY")

在此处查看更多信息:https://momentjs.com/docs/#/parsing/string-formats/

答案 1 :(得分:1)

dayOfWeek = moment(dayOfWeek).format("dddd, DD-MM-YYYY");

答案 2 :(得分:1)

您的代码将失败,因为dayOfWeek不是moment对象。

要检查您的变量是否为moment对象,请使用.isMoment

moment.isMoment(dayOfWeek)

要解决您的问题,只需替换

dayOfWeek.format("dddd, DD-MM-YYYY")

使用

moment(dayOfWeek).format("dddd, DD-MM-YYYY")

您还缺少return函数中的.map语句。

工作示例:

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>

答案 3 :(得分:0)

提示,您也可以这样做

var currentDate = moment(new Date()); // pass your date obj here.
console.log(currentDate.format('DD-MM-YY HH:mm:ss')); // later simply do this.
<script src="https://unpkg.com/moment@2.22.2/min/moment.min.js"></script>