js统计网站运行时长

云游道人 2025-05-30 14 阅读 0评论


<p id="RunTime"></p>

<script>

var myVar=setInterval(function(){myTimer()},1000);

function myTimer(){

var d=new Date();

var t=d.toLocaleTimeString();

var dangqian = d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate() ;

document.getElementById("RunTime").innerHTML="本站已运行:"+ DateDiff("2023-12-05",dangqian) +" :" + t;

}

/* 计算运行天数的封装函数 */

function  DateDiff(sDate1,  sDate2){    //sDate1和sDate2是2002-12-18格式  

    // 标准化日期解析(避免字符串分割风险)

    const parseDate = (str) => {

        const [year, month, day] = str.split("-");

        return new Date(year, month - 1, day); // 月份从0开始

    };


    const startDate = parseDate(sDate1);

    const endDate = parseDate(sDate2);

    

    // 计算总天数差

    const timeDiff = Math.abs(endDate - startDate);

    const totalDays = Math.floor(timeDiff / (1000 * 3600 * 24));


    // 精确计算年数和剩余天数(考虑闰年)

    let years = 0, days = totalDays;

    while (days >= 365) {

        const nextYearDate = new Date(startDate);

        nextYearDate.setFullYear(startDate.getFullYear() + years + 1);

        if (nextYearDate > endDate) break;

        years++;

        days = Math.floor((endDate - nextYearDate) / (1000 * 3600 * 24)) + 1;

    }


    return years > 0 ? `${years} 年 ${days} 天` : `${days} 天`;

}

</script>


发表评论

快捷回复: 表情:
Addoil Applause Badlaugh Bomb Coffee Fabulous Facepalm Feces Frown Heyha Insidious KeepFighting NoProb PigHead Shocked Sinistersmile Slap Social Sweat Tolaugh Watermelon Witty Wow Yeah Yellowdog
提交
评论列表 (有 0 条评论, 14人围观)

最近发表

热门文章

最新留言

热门推荐

标签列表