JS之Date函数获取时间代码

JS之Date函数获取时间代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JS之Date函数获取时间代码</title>
</head>
<body>
<script>
    /************ JS之Date函数获取时间代码 *************/
    //自定义函数,判断数字如果小于10,前面加个0
    function check(x){
    if(x<10){
    return '0'+x;
    }
    return x;
    }
    //实例化Date方法
    var time = new Date();
    //获取年
    var year = time.getFullYear();
    //获取月
    var month = time.getMonth()+1;  //返回0~11的数
    //获取日
    var day = time.getDay();
    //获取时
    var hour = check(time.getHours());
    //获取分
    var minute = check(time.getMinutes());
    //获取秒
    var second = check(time.getSeconds());
    //输出结果
    console.log(year+'-'+month+'-'+day+' '+hour+':'+minute+':'+second); //结果:2018-10-4 23:16:54
</script>
</body>
</html>
Copyright [2018] by [羊驼可以吃吗] form [https://www.cnblogs.com/phpisfirst/]
原文地址:https://www.cnblogs.com/phpisfirst/p/9792548.html