方法1:slice截取
const date = '2023-07-17 16:52:32';
const monthAndDay = date.slice(5, 10);
console.log(monthAndDay); // 输出 07-17
方法2:使用Date对象的方法来提取日期
使用JavaScript的Date对象来解析日期字符串,并使用其方法来获取日期部分
const date = '2023-07-17 16:52:32';
const parsedDate = new Date(date);
const day = parsedDate.getDate();
const month = parsedDate.getMonth() + 1; // 月份从0开始,所以需要加1
const formattedDate = `${month < 10 ? '0' + month : month}-${day < 10 ? '0' + day : day}`;
console.log(formattedDate); // 输出 07-17
这段代码首先使用new Date(date)来创建一个Date对象,将日期字符串解析为日期。然后,使用getDate()方法获取日期部分,使用getMonth()方法获取月份部分(注意月份从0开始,所以需要加1)。最后,使用模板字符串将月份和日期格式化为MM-DD的形式。
这种方法更灵活,可以适应不同格式的日期字符串,并且不需要手动截取字符串。
方法3:使用正则表达式来匹配日期部分
const date = '2023-07-17 16:52:32';
const regex = /(\d{4})-(\d{2})-(\d{2})/;
const match = date.match(regex);
const formattedDate = `${match[2]}-${match[3]}`;
console.log(formattedDate); // 输出 07-17
这段代码使用正则表达式/(\d{4})-(\d{2})-(\d{2})/来匹配日期部分。然后,使用match()方法将日期字符串与正则表达式进行匹配,返回一个数组。数组的第一个元素是完整的匹配结果,后续元素是每个捕获组的匹配结果。在这种情况下,我们只关心日期部分,所以使用match[2]和match[3]来获取月份和日期。最后,使用模板字符串将月份和日期格式化为MM-DD的形式。
这种方法也是一种灵活的方式,可以适应不同格式的日期字符串,并且可以根据需要进行更复杂的正则表达式匹配。
本文介绍了三种在JavaScript中提取和格式化日期的方法:使用slice截取字符串,通过Date对象的方法,以及利用正则表达式匹配。这些方法灵活且适用于不同格式的日期字符串。
2907

被折叠的 条评论
为什么被折叠?



