js获取当前年月并且处理成yyyy-MM格式
可以使用Date对象来获取当前年月,然后使用字符串拼接的方法将其处理成指定格式的字符串。
示例代码如下:
var date = new Date(); //获取当前时间
var year = date.getFullYear(); //获取当前年份
var month = date.getMonth() + 1; //获取当前月份(注意:月份从0开始,需要加上1)
if (month < 10) { //如果月份小于10,前面补0
month = '0' + month;
}
var yearMonth = year + '-' + month; //拼接成yyyy-MM格式的字符串
console.log(yearMonth); //输出结果:2022-08
原文地址: https://www.cveoy.top/t/topic/7Cn 著作权归作者所有。请勿转载和采集!