Home > Web Front-end > JS Tutorial > javascript gets current date

javascript gets current date

王林
Release: 2020-05-07 09:21:59
forward
2711 people have browsed it

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>
Copy after login

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!

Related labels:
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Issues
What is JavaScript garbage collection?
From 1970-01-01 08:00:00
0
0
0
What are JavaScript hook functions?
From 1970-01-01 08:00:00
0
0
0
c++ calls javascript
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template