能帮我用JS写一个获取当前日期时间的代码吗
时间: 2023-04-01 11:04:07 浏览: 86
可以的,以下是获取当前日期时间的 JS 代码:
var now = new Date();
var year = now.getFullYear(); //获取完整的年份(4位,197-????)
var month = now.getMonth() + 1; //获取当前月份(-11,代表1月)
var date = now.getDate(); //获取当前日(1-31)
var hour = now.getHours(); //获取当前小时数(-23)
var minute = now.getMinutes(); //获取当前分钟数(-59)
var second = now.getSeconds(); //获取当前秒数(-59)
var datetime = year + "-" + month + "-" + date + " " + hour + ":" + minute + ":" + second;
console.log(datetime); //输出当前日期时间
相关问题
我需要用js写一个获取当前时间的代码
好的,以下是获取当前时间的JS代码:
```javascript
const now = new Date();
const year = now.getFullYear(); // 获取当前年份
const month = now.getMonth() + 1; // 获取当前月份(注意getMonth返回的是0-11,需要加1)
const day = now.getDate(); // 获取当前日期
const hour = now.getHours(); // 获取当前小时
const minute = now.getMinutes(); // 获取当前分钟
const second = now.getSeconds(); // 获取当前秒数
console.log(`${year}-${month}-${day} ${hour}:${minute}:${second}`);
```
以上代码会输出当前时间,格式为 `yyyy-mm-dd hh:mm:ss`。
帮我写一个在线日期时间的网页代码
好的,以下是一个简单的在线日期时间的网页代码:
```html
<!DOCTYPE html>
<html>
<head>
<title>在线日期时间</title>
<script>
function updateTime() {
var now = new Date();
var date = now.toLocaleDateString();
var time = now.toLocaleTimeString();
document.getElementById("date").innerHTML = date;
document.getElementById("time").innerHTML = time;
}
setInterval(updateTime, 1000);
</script>
</head>
<body>
<h1>当前日期时间:</h1>
<p>日期:<span id="date"></span></p>
<p>时间:<span id="time"></span></p>
</body>
</html>
```
这个代码使用 JavaScript 获取当前日期时间,并在网页中显示出来。每秒钟会自动更新一次。