在外卖和电影等项目中会用到特殊的时间格式。
// 封装函数得到数据格式
/*
09-09:'今天'
09-10:'明天'
09-11:'后天'
09-12:'周三'
09-13:'周四'
09-14:'周五'
*/
function createDate() {
// 定义一个对象存放构建的数据格式
const dayObj = {}
// 定义存放今天、明天、后天的数组
const dayStrs = ['今天', '明天', '后天']
// 定义星期数组
const weekDays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
// 循环遍历近七天
for (let i = 0; i < 7; i++) {
let date = new Date()//获取当前时间对象
date.setTime(date.getTime() + 24 * 60 * 60 * 1000 * i)//getTime通过当前时间对象获取时间,加上对应天数时间戳,setTime转换为时间戳
// 声明一个变量存储:获取当前的月份
let nowDay = date.getMonth() + 1 > 9 ? date.getMonth() + 1 : '0' + (date.getMonth() + 1)
// 将天数累加到声明的变量中
nowDay += date.getDate() > 9 ? date.getDate() : '0' + date.getDate()
// 今明后三天012
if (i < 3) {
// 每循环一次就将获得的数据添加到对象中
dayObj[nowDay] = dayStrs[i]
} else {
let weekDay = date.getDay()
// 将星期赋值给对象
dayObj[nowDay] = weekDays[weekDay]
}
}
// console.log(dayObj);
return dayObj;
}
console.log(createDate());