JavaScript日期格式转换:将“2006年10月31日”转换为“2006-10-31”
你可以使用 JavaScript 中的 Date 对象来处理日期的转换。以下是一个封装的方法,将/'2006年10月31日/'转换为/'2006-10-31/'的格式:/n/njavascript/nfunction formatDate(dateString) {/n // 使用正则表达式提取年、月、日/n const regex = /(/d{4})年(/d{1,2})月(/d{1,2})日/; /n const matches = dateString.match(regex);/n /n // 如果匹配成功/n if (matches) {/n // 提取年、月、日/n const year = matches[1];/n const month = matches[2].padStart(2, '0');/n const day = matches[3].padStart(2, '0');/n /n // 返回转换后的日期字符串/n return `${year}-${month}-${day}`;/n }/n /n // 如果匹配失败,返回原始字符串/n return dateString;/n}/n/n// 调用方法/nconsole.log(formatDate(/'2006年10月31日/')); // 输出 /'2006-10-31/'/n/n/n这个方法使用正则表达式提取年、月和日,并使用字符串的 padStart 方法在月和日前补充 0,以确保日期的格式正确。如果输入的字符串格式不匹配,将返回原始字符串。
原文地址: https://www.cveoy.top/t/topic/pVlp 著作权归作者所有。请勿转载和采集!