如何将JavaScript生成的日期转换为YYYY-MM-DD格式?
解决日期格式转换为YYYY-MM-DD的方案
下面提供两种可靠的方法来将日期转换为2023-05-31格式:
方法一:直接从Date对象提取拼接(推荐)
这种方法不依赖区域设置(locale)的输出格式,彻底避免环境差异导致的问题,兼容性和稳定性最优:
const lastDayDate = new Date(selectedDate.getFullYear(), selectedDate.getMonth() + 1, 0); const year = lastDayDate.getFullYear(); // 月份是0索引(0-11),加1后用padStart补零到2位 const month = String(lastDayDate.getMonth() + 1).padStart(2, '0'); // 日期直接补零到2位 const day = String(lastDayDate.getDate()).padStart(2, '0'); const formattedDate = `${year}-${month}-${day}`; console.log(formattedDate); // 输出示例:2023-05-31
方法二:基于现有locale输出拆分重组
如果想基于当前得到的05/31/2023格式直接转换,可以拆分字符串后重新拼接:
const lastDayDate = new Date(selectedDate.getFullYear(), selectedDate.getMonth() + 1, 0); const options = { year: 'numeric', month: '2-digit', day: '2-digit' }; const rawFormatted = lastDayDate.toLocaleDateString('se-SE', options); // 按斜杠拆分,得到 [月份, 日期, 年份] const [month, day, year] = rawFormatted.split('/'); const formattedDate = `${year}-${month}-${day}`; console.log(formattedDate); // 输出示例:2023-05-31
注意:方法二依赖当前locale输出的顺序是
MM/DD/YYYY,如果环境中se-SE的输出格式变化,该方法会失效,因此更推荐方法一。
内容的提问来源于stack exchange,提问作者William
相关产品推荐
相关产品推荐

