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

javascript gets current date

王林
Release: 2020-05-07 09:21:59
forward
2500 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:
source:cnblogs.com
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template