当我们把日期转换为Number类型的时候,就会变成时间戳(毫秒)
const future = new Date(2037, 10, 19, 15, 23);
console.log(Number(future));
// console.log(+future); //与上行代码等效
● 所以我们就可以利用时间戳去做点东西,例如你的女朋友给你两个时间,一个时间是第一次约会的时间,第二个时间是第二次约会的时间,问你第一次约会和第二次约会间隔多少天?
const calcDaysPassed = (date1, date2) =>
(date2 - date1) / (1000 * 60 * 60 * 24);
const day1 = calcDaysPassed(new Date(2037, 3, 4), new Date(2037, 3, 14));
console.log(day1);
但是为了防止出现负数,我们还是给加上绝对值
const calcDaysPassed = (date1, date2) => //定义一个函数,可以传两个参数
Math.abs(date2 - date1) / (1000 * 60 * 60 * 24); //用参数2减去参数1,然后取绝对值,最后转换为天数
const day1 = calcDaysPassed(new Date(2037, 3, 4), new Date(2037, 3, 14)); //传值
console.log(day1); //打印
实例
现在我们将我们学习的知识加到我们实际的项目上去
之前我们制作好了这个时间,但是我们现在想时间如果这个时间是今天,就显示今天,不必显示详细时间,昨天显示昨天,类似这样
movs.forEach(function (mov, i) {
const type = mov > 0 ? 'deposit' : 'withdrawal';
const date = new Date(acc.movementsDates[i]);
const day = `${date.getDate()}`.padStart(2, 0);
const month = `${date.getMonth() + 1}`.padStart(2, 0);
const year = date.getFullYear();
const displayDate = `${day}/${month}/${year}`;
const html = `
<div class="movements__row">
<div class="movements__type movements__type--${type}">${
i + 1
} ${type}</div>
<div class="movements__date">${displayDate}</div>
<div class="movements__value">${mov.toFixed(2)}€</div>
</div>
`;
containerMovements.insertAdjacentHTML('afterbegin', html);
});
};
这个是我们之前的代码,现在我们将时间定义的拿走,不然我们没法直接定义
const formatMovementDate = function (date) {
const calcDaysPassed = (date1, date2) =>
Math.round(Math.abs(date2 - date1) / (1000 * 60 * 60 * 24));
const daysPassed = calcDaysPassed(new Date(), date);
if (daysPassed === 0) return '今天'; //如果天数等于0,那就输出今天
if (daysPassed === 1) return '昨天'; //如果天数等于1,那就输出昨天
if (daysPassed <= 7) return `${daysPassed} 天前`;//如果天数小于等于七天,那就输出几天内
const day = `${date.getDate()}`.padStart(2, 0); //如果上面都不匹配的话,我们直接输出真实的时间
const month = `${date.getMonth() + 1}`.padStart(2, 0);
const year = date.getFullYear();
return `${day}/${month}/${year}`;
};
const displayMovements = function (acc, sort = false) {
containerMovements.innerHTML = '';
const movs = sort
? acc.movements.slice().sort((a, b) => a - b)
: acc.movements;
movs.forEach(function (mov, i) {
const type = mov > 0 ? 'deposit' : 'withdrawal';
const date = new Date(acc.movementsDates[i]);
const displayDate = formatMovementDate(date);
const html = `
<div class="movements__row">
<div class="movements__type movements__type--${type}">${
i + 1
} ${type}</div>
<div class="movements__date">${displayDate}</div>
<div class="movements__value">${mov.toFixed(2)}€</div>
</div>
`;
containerMovements.insertAdjacentHTML('afterbegin', html);
});
};