我正在尝试使用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")
});
答案 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>