欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

时间函数

程序员文章站 2022-03-09 23:39:51
...

时间函数一直记得比较混乱,所以抽时间好好学习了一下,下面是自己练手的一段输出当前时间的代码~

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>date</title>
</head>

<body>
    <span id="dateText"></span>
</body>
<script type="text/javascript">
    var spanObj = document.getElementById('dateText');
    var time = new Date();
    var year = time.getFullYear();
    var month = time.getMonth() + 1;
    month.toString().length == 1 && (month = '0' + month)
    var date = time.getDate()
    date.toString().length == 1 && (date = '0' + date)
    var day = time.getDay()
    var week = [{
        condition: 1,
        default: '一'
    }, {
        condition: 2,
        default: '二'
    }, {
        condition: 3,
        default: '三'
    }, {
        condition: 4,
        default: '四'
    }, {
        condition: 5,
        default: '五'
    }, {
        condition: 6,
        default: '六'
    }, {
        condition: 7,
        default: '日'
    }]
    var nowDay = week.filter(item => {
        return item.condition == day
    })[0].default
    var hour = time.getHours()
    hour.toString().length == 1 && (hour = '0' + hour)

    var minutes = time.getMinutes()
    minutes.length == 1 && (minutes = '0' + minutes)

    var seconds = time.getSeconds()
    seconds.toString().length == 1 && (seconds = '0' + seconds)
    var milliseconds = time.getMilliseconds()
    var timeStr = '现在是北京时间:' + year + '年' + month + '月' + date + '日' + '\xa0\xa0' + '星期' + nowDay +
        '\xa0\xa0' + //在js字符串中加空格\xa0
        hour + ':' + minutes + ':' + seconds
    spanObj.textContent = timeStr
</script>

</html>
相关标签: 时间函数 前端