在 web 开发中, 通过 JS 获取时间非常的常用. 下面本篇文章就来给大家介绍一下使用 JavaScript 获取当前时间的方法, 希望对大家有所帮助.
在 JavaScript 中可以使用 Date 对象中的 Date() 方法来获取当前时间. Date() 方法可返回当天的日期和时间.
Date()
示例: 输出今天的日期和时间
- <script type="text/javascript">
- document.write(Date())
- </script>
输出:
Tue Aug 20 2019 18:24:16 GMT+0800 (中国标准时间)
或者使用 Date 对象中不同方法, 格式化时间, 以固定格式显示时间.
创建 Date 对象:
var date = new Date();
示例: 获取当前时间的年, 月, 日, 星期如下:
- <!DOCTYPE html>
- <HTML>
- <head>
- <meta charset="UTF-8">
- </head>
- <body>
- <div id="timer">
- </div>
- <script type="text/javascript">
- function current() {
- var d = new Date(),
- str = '';
- str += d.getFullYear() + '年'; // 获取当前年份
- str += d.getMonth() + 1 + '月'; // 获取当前月份 (0--11)
- str += d.getDate() + '日';
- str += d.getHours() + '时';
- str += d.getMinutes() + '分';
- str += d.getSeconds() + '秒';
- return str;
- }
- Windows.onload = function() {
- var timer = document.getElementById("timer");
- timer.innerHTML = current();
- }
- </script>
- </body>
- </HTML>
输出:
2019 年 8 月 20 日 18 时 24 分 2 秒
来源: http://www.css88.com/qa/javascript/11407.html