js实时获取当前时间、2周前、3月前

版权声明:本篇博客内容来源于本人亲身经历,属于本人原创,转载请注明出处,感谢分享~~ https://blog.csdn.net/hl_qianduan/article/details/86530290
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>js实时获取当前时间、2周前、3月前</title>
</head>
<body>
<script>
    var dt = new Date();
    function nowtime(dt){
          return dt.getFullYear() + "-" +
            (((dt.getMonth() + 1)<10)?("0" + (dt.getMonth()+1)) : (dt.getMonth()+1))
            + "-" +((dt.getDate()<10)?("0" + dt.getDate()) : dt.getDate())
            +" "+((dt.getHours()<10)?("0" + dt.getHours()) : dt.getHours())
            +":"+((dt.getMinutes()<10)?("0" + dt.getMinutes()) : dt.getMinutes())
            +":"+((dt.getSeconds()<10)?("0" + dt.getSeconds()) : dt.getSeconds());
    }

    var dtt = new Date();
    dtt.setMonth(dtt.getMonth() - 3);
    var current = nowtime(dtt);


    document.write("当前时间:"+nowtime(dt)+"<br>");
    document.write("两周前:"+getDay(-14)+"<br>");
    document.write("三月前:"+current);
    
    function getDay(day) {
        var today = new Date();
        var targetday_milliseconds = today.getTime() + 1000 * 60 * 60 * 24 * day;
        today.setTime(targetday_milliseconds); //注意,这行是关键代码
        var tYear = today.getFullYear();
        var tMonth = today.getMonth();
        var tDate = today.getDate();
        var tHours = today.getHours();
        var tMinutes = today.getMinutes();
        var tSeconds = today.getSeconds();
        tMonth = doHandleMonth(tMonth + 1);
        tDate = doHandleMonth(tDate);
        tHours = doHandleMonth(tHours);
        tMinutes = doHandleMonth(tMinutes);
        tSeconds = doHandleMonth(tSeconds);
        return tYear + "-" + tMonth + "-" + tDate+" "+tHours+":"+tMinutes+":"+tSeconds;
    }
    function doHandleMonth(month) {
        var m = month;
        if (month.toString().length == 1) {
            m = "0" + month;
        }
        return m;
    }
</script>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/hl_qianduan/article/details/86530290