js 获取当前年月日时分秒
时间: 2023-10-24 13:04:47 浏览: 37
你可以使用以下代码获取当前年月日时分秒:
```javascript
const now = new Date();
const year = now.getFullYear();
const month = now.getMonth() + 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}`);
```
请注意,这仅适用于JavaScript。如果你需要在其他编程语言中获取当前日期和时间,可能需要使用不同的代码。
相关问题
js获取当前年月日时分秒
你可以使用 JavaScript 的 `Date` 对象来获取当前的年、月、日、时、分、秒。下面一个示例:
```javascript
let currentDate = new Date();
let year = currentDate.getFullYear();
let month = currentDate.getMonth() + 1; // 注意月份是从 0 开始的,所以要加 1
let day = currentDate.getDate();
let hour = currentDate.getHours();
let minute = currentDate.getMinutes();
let second = currentDate.getSeconds();
console.log(year, month, day, hour, minute, second);
```
在这个示例中,`new Date()` 创建了一个当前日期和时间的 `Date` 对象。然后,使用 `getFullYear()`、`getMonth()`、`getDate()`、`getHours()`、`getMinutes()` 和 `getSeconds()` 方法来获取相应的年、月、日、时、分、秒。最后,使用 `console.log()` 打印输出这些值。
请注意,月份是从 0 开始计数的,所以在获取月份时需要加 1。
js获取当前年月日时分秒拼接字符串
可以使用 JavaScript 的 Date 对象来获取当前的年月日时分秒,然后将它们拼接成一个字符串。以下是一个例子:
```javascript
const date = new Date();
const year = date.getFullYear();
const month = ('0' + (date.getMonth() + 1)).slice(-2);
const day = ('0' + date.getDate()).slice(-2);
const hours = ('0' + date.getHours()).slice(-2);
const minutes = ('0' + date.getMinutes()).slice(-2);
const seconds = ('0' + date.getSeconds()).slice(-2);
const dateString = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
console.log(dateString);
```
输出结果类似于:`2021-08-31 13:45:23`。
这里使用了 `slice` 函数来确保月、日、时、分、秒的两位数格式,如果不足两位则在前面添加 0。