Home  >  Article  >  Web Front-end  >  javascript gets current date

javascript gets current date

王林
王林forward
2020-05-07 09:21:592454browse

javascript gets current date

Let’s look directly at the example code:

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        //返回时间格式:年-月-日 时:分:秒
        function getDateString(date) {
            // 获取传入的时间,若没有传值则取当前时间
            var dateStr = date || new Date();

            // 获取时间的年月日
            var year = dateStr.getFullYear().toString().padStart(4, "0");
            var month = (dateStr.getMonth() + 1).toString().padStart(2, "0");
            var day = dateStr.getDate().toString().padStart(2, "0");

            // 获取时间的时分秒
            var hour = dateStr.getHours().toString().padStart(2, "0");
            var minute = dateStr.getMinutes().toString().padStart(2, "0");
            var second = dateStr.getSeconds().toString().padStart(2, "0");

            //返回时间格式:年-月-日 时:分:秒
            return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
        }
        console.log(getDateString());
    </script>
</body>

</html>

Recommended tutorial: js entry tutorial

The above is the detailed content of javascript gets current date. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete