在 Vue 中获取上上周日和上周六的日期,并将其转换为 "年月日" 格式的字符串,可以通过以下步骤实现:
方法一:使用 JavaScript 的 Date 对象
获取当前日期。
计算上上周日和上周六的日期。
格式化日期为 "年月日" 格式。
示例代码:
export default {name: 'ExampleComponent',methods: {getDates() {const today = new Date();// 获取今天的星期几const todayDayOfWeek = today.getDay(); // 0 表示周日,6 表示周六// 计算上周六的日期const lastSaturday = new Date(today);lastSaturday.setDate(today.getDate() - (todayDayOfWeek === 0 ? 6 : todayDayOfWeek));// 计算上上周日的日期const secondLastSunday = new Date(lastSaturday);secondLastSunday.setDate(lastSaturday.getDate() - 7);// 格式化日期const format = date => {const year = date.getFullYear();let month = date.getMonth() + 1; // 月份是从 0 开始的let day = date.getDate();if (month < 10) month = '0' + month;if (day < 10) day = '0' + day;return `${year}-${month}-${day}`;};const lastSaturdayFormatted = format(lastSaturday);const secondLastSundayFormatted = format(secondLastSunday);return {lastSaturday: lastSaturdayFormatted,secondLastSunday: secondLastSundayFormatted};}}
}