js获取当前年月日时分秒拼接字符串
时间: 2023-06-28 10:04:03 浏览: 124
可以使用 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。
相关问题
js获取当前时间年月日时分秒 代码简洁明了
以下是获取当前时间年月日时分秒的JavaScript代码,代码简洁明了:
```javascript
let date = new Date();
let year = date.getFullYear();
let month = date.getMonth() + 1;
let day = date.getDate();
let hour = date.getHours();
let minute = date.getMinutes();
let second = date.getSeconds();
let currentDateTime = year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second;
```
以上代码中,我们使用了JavaScript内置的Date对象来获取当前时间,然后通过调用Date对象的方法来获取年、月、日、时、分、秒等信息,并将它们拼接成一个字符串,最终得到了当前时间的年月日时分秒。
js获取年月日时分秒
可以使用JavaScript中的Date对象来获取当前的年月日时分秒。以下是获取年月日时分秒的代码示例:
```javascript
var now = new Date();
var year = now.getFullYear(); //获取完整的年份(4位)
var month = now.getMonth() + 1; //获取当前月份(0-11, 0代表1月)
var date = now.getDate(); //获取当前日(1-31)
var hour = now.getHours(); //获取当前小时数(0-23)
var minute = now.getMinutes(); //获取当前分钟数(0-59)
var second = now.getSeconds(); //获取当前秒数(0-59)
```
其中,getMonth()方法返回的是0-11的数字,需要加1才能得到实际的月份。如果需要格式化输出时间,可以使用字符串拼接等方法实现。