javascript date获取时间
时间: 2023-08-15 12:06:54 浏览: 50
要在JavaScript中获取当前时间,你可以使用Date对象。以下是一个示例代码:
```javascript
// 创建一个Date对象
const currentDate = new Date();
// 获取当前时间的各个部分
const year = currentDate.getFullYear();
const month = currentDate.getMonth() + 1; // 月份从0开始,所以要加1
const day = currentDate.getDate();
const hours = currentDate.getHours();
const minutes = currentDate.getMinutes();
const seconds currentDate.getSeconds();
// 输出当前时间
console.log(`当前时间:${year}-${month}-${day} ${hours}:${minutes}:${seconds}`);
```
这个代码将获取当前时间并将其拆分为年、月、日、小时、分钟和秒。你可以根据需要使用这些变量进行进一步的操作。
相关问题
js new date获取时间
在JavaScript中,可以使用`new Date()`来获取当前的日期和时间。如果需要获取特定日期和时间,可以使用`new Date(year, month, day, hours, minutes, seconds, milliseconds)`构造函数。其中,年份和月份是必需的,其他参数是可选的。如果省略了其他参数,则它们将被设置为0。以下是一些例子:
1. 获取当前日期和时间
```javascript
var now = new Date();
console.log(now.toLocaleString()); // 输出:2022/5/14 08:45:25
```
2. 获取特定日期和时间
```javascript
var date = new Date(2022, 4, 14, 9, 30, 0, 0);
console.log(date.toLocaleString()); // 输出:2022/5/14 09:30:00
```
3. 将日期字符串转换为时间戳
```javascript
var dateStr = '2015-03-05 17:59:00.0';
dateStr = dateStr.substring(0, 19);
dateStr = dateStr.replace(/-/g, '/');
var timestamp = new Date(dateStr).getTime();
console.log(timestamp); // 输出:1425530340000
```
javascript+获取当前时间
以下是两种JavaScript获取当前时间的方法:
1. 使用Date对象获取当前时间
```javascript
var currentDate = new Date();
var year = currentDate.getFullYear();
var month = ("0" + (currentDate.getMonth() + 1)).slice(-2);
var day = ("0" + currentDate.getDate()).slice(-2);
var hour = ("0" + currentDate.getHours()).slice(-2);
var minute = ("0" + currentDate.getMinutes()).slice(-2);
var second = ("0" + currentDate.getSeconds()).slice(-2);
var currentTime = year + month + day + hour + minute + second;
console.log(currentTime); // 输出:当前时间的yyyymmddhhmmss格式
```
2. 使用document.lastModified属性获取当前网页最后修改时间
```javascript
var lastModified = document.lastModified;
console.log(lastModified); // 输出:当前网页最后修改时间
```