js换算当前时间与某一时间差剩余几年几月几周几日几时几分几秒

代码复制即用

/**
 * @M楸MOAQ
 * 
 * 时间差换算
 *  */

export const handlePublishTimeDesc = (post_modified: string) => {
    const targetDate = new Date(post_modified);
	/*获取当前时间*/ 
    const currentDate = new Date();

    /*计算时间差*/ 
    let timeDiff = targetDate.getTime() - currentDate.getTime();
  
    /*计算年、月、周、天、小时、分钟和秒*/ 
    const years = Math.floor(timeDiff / (1000 * 60 * 60 * 24 * 365));
    timeDiff -= years * (1000 * 60 * 60 * 24 * 365);
    const months = Math.floor(timeDiff / (1000 * 60 * 60 * 24 * 30));
    timeDiff -= months * (1000 * 60 * 60 * 24 * 30);
    const weeks = Math.floor(timeDiff / (1000 * 60 * 60 * 24 * 7));
    timeDiff -= weeks * (1000 * 60 * 60 * 24 * 7);
    const days = Math.floor(timeDiff / (1000 * 60 * 60 * 24));
    timeDiff -= days * (1000 * 60 * 60 * 24);
    const hours = Math.floor(timeDiff / (1000 * 60 * 60));
    timeDiff -= hours * (1000 * 60 * 60);
    const minutes = Math.floor(timeDiff / (1000 * 60));
    timeDiff -= minutes * (1000 * 60);
    const seconds = Math.floor(timeDiff / 1000);
    console.log(years, "年", months, "月", weeks + "周" + days + "日" + hours + "时" + minutes + "分" + seconds + "秒")
    if (years > 0) {
        return `${years}年${months}月${weeks}周${days}日${hours}时${minutes}分${seconds}秒`
    } else if (months > 0) {
        return `${months}月${weeks}周${days}日${hours}时${minutes}分${seconds}秒`
    } else if (weeks > 0) {
        return `${weeks}周${days}日${hours}时${minutes}分${seconds}秒`
    } else if (days > 0) {
        return `${days}日${hours}时${minutes}分${seconds}秒`
    } else if (hours > 0) {
        return `${hours}时${minutes}分${seconds}秒`
    } else if (minutes > 0) {
        return `${minutes}分${seconds}秒`
    } else if (seconds > 0) {
        return `${seconds}秒`
    } else {
        return "已结束"
    }
}

你可能感兴趣的:(javascript,前端,开发语言)