js时间戳

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

<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>

<body>
    <script type="text/javascript">
    /*
                *一、时间转换时间戳

                */
    var date = new Date(); //时间对象
    var str = date.getTime(); //转换成时间戳
    console.log(str);
    /*
    *二、时间戳转换为时间

    */
    // 转换成形如 ‎2018‎年‎1‎月‎4‎日‎ ‎14‎:‎00‎:‎00 格式:
    function getDate(date) {
        var t = new Date(date).toLocaleString();
        return t;

    }
    console.log(getDate(date));
    //
    // 也很简单
    var strtime = '2014-04-23 18:55:49:123';

    var date = new Date(strtime.replace(/-/g, '/'));

    // 有三种方式获取,在后面会讲到三种方式的区别
    time1 = date.getTime();
    time2 = date.valueOf();
    time3 = Date.parse(date);
    console.log(time1)
    console.log(time2)
    console.log(time3)

    /* 
    三种获取的区别:
    第一、第二种:会精确到毫秒
    第三种:只能精确到秒,毫秒将用0来代替
    比如上面代码输出的结果(一眼就能看出区别):
    1398250549123
    1398250549123
    1398250549000 
    */
    //
    // 比如需要这样的格式 yyyy-MM-dd hh:mm:ss
    var date = new Date(1398250549490);
    Y = date.getFullYear() + '-';
    M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
    D = date.getDate() + ' ';
    h = date.getHours() + ':';
    m = date.getMinutes() + ':';
    s = date.getSeconds(); 
    console.log(Y+M+D+h+m+s); 
    // 输出结果:2014-04-23 18:55:49
    </script>
</body>

</html>

效果图:

原链接:https://www.cnblogs.com/Donnnnnn/p/8257493.html

猜你喜欢

转载自www.cnblogs.com/huanghuali/p/9336549.html
今日推荐