- 20
- 0
- 约1.09千字
- 约 2页
- 2023-08-02 发布于陕西
- 举报
js 获取当前时间的年月日并转为指定
格式字符串
在JavaScript 中,你可以使用Date 对象来获取当前时间的年、
月、日,并将其转换为指定的格式字符串。以下是获取当前时间的年、
月、日,并转换为指定格式字符串的示例代码:
// 获取当前时间的年、月、日
const currentDate = new Date();
const year = currentDate.getFullYear(); // 获取年份,例
如:2023
const month = currentDate.getMonth() + 1; // 获取月份
(注意:月份从0 开始,所以要加1),例如:7
const day = currentDate.getDate(); // 获取日期,例如:31
// 将年、月、日转为指定格式的字符串(格式为:YYYY-MM-DD)
const formattedDate = `${year}-
${month.toString().padStart(2,
原创力文档

文档评论(0)