JS里面写一个获取当天日期的函数
时间: 2024-05-02 13:19:14 浏览: 18
可以使用以下代码获取当天日期:
```javascript
function getCurrentDate() {
const date = new Date();
const year = date.getFullYear();
const month = (date.getMonth() + 1).toString().padStart(2, '0');
const day = date.getDate().toString().padStart(2, '0');
return `${year}-${month}-${day}`;
}
console.log(getCurrentDate()); // 输出格式为:YYYY-MM-DD,例如:2022-01-01
```
希望这个回答能帮到你!
相关问题
js写一个获取今天的函数
以下是获取今天日期的JavaScript函数:
```javascript
function getTodayDate() {
let today = new Date(); // 获取当前日期
let year = today.getFullYear(); // 获取年份
let month = today.getMonth() + 1; // 获取月份,注意要加1
let day = today.getDate(); // 获取日期
return year + "-" + month + "-" + day; // 返回格式化后的结果
}
```
调用该函数可以返回当前日期,例如:
```javascript
console.log(getTodayDate()); // 输出:2021-10-25
```
js获取当前日期的函数
可以使用 JavaScript 的 Date 对象来获取当前日期,可以使用以下代码:
```
const currentDate = new Date();
const year = currentDate.getFullYear();
const month = currentDate.getMonth() + 1; // 月份从0开始计算,需要加1
const day = currentDate.getDate();
console.log(`${year}-${month}-${day}`);
```
这段代码会输出当前的年月日,例如:2021-08-25。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)