以下是一个简单的实现:

// 目标日期
const targetDate = new Date('2023-05-01');

// 获取当前时间
const now = new Date();

// 计算时间差,单位为毫秒
const timeDiff = targetDate.getTime() - now.getTime();

// 将时间差转换为天数
const days = Math.floor(timeDiff / (24 * 60 * 60 * 1000));

// 将天数转换为字符串,补零至两位
const daysString = ('00' + days).slice(-2);

// 将时间差转换为小时数
const hours = Math.floor((timeDiff % (24 * 60 * 60 * 1000)) / (60 * 60 * 1000));

// 将小时数转换为字符串,补零至两位
const hoursString = ('00' + hours).slice(-2);

// 将时间差转换为分钟数
const minutes = Math.floor((timeDiff % (60 * 60 * 1000)) / (60 * 1000));

// 将分钟数转换为字符串,补零至两位
const minutesString = ('00' + minutes).slice(-2);

// 将时间差转换为秒数
const seconds = Math.floor((timeDiff % (60 * 1000)) / 1000);

// 将秒数转换为字符串,补零至两位
const secondsString = ('00' + seconds).slice(-2);

// 输出倒计时
console.log(`${daysString}天 ${hoursString}小时 ${minutesString}分钟 ${secondsString}秒`);

输出结果为:

724天 12小时 42分钟 16秒
用js写一个到2023-5-1日还有多少时间的倒计时

原文地址: https://www.cveoy.top/t/topic/8JG 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录