如何使用 moment.js 从这个 iso 格式的结构中获取开始和结束日期?

How to get start and end dates from this iso formated structure using moment.js?

我有 related.date: {"isoYear":"2021","isoWeek":"31"} 属性 从后端收到以下值。如何使用 momenjs 从 isoWeek 31 接收 isoYear 的第一个日期和最后一个日期?

const date = moment().isoWeek(related.date.isoWeek).year(related.date.year)
const first = moment().weekday(0)
const last = moment().weekday(6)

默认工作日 0 是星期日,如果你住在第一个工作日是星期一的地区,你必须自己解析或使用配置 moment-with-locales-es6

您可以使用 startOf('isoWeek').

// related.date: {"isoYear":"2021","isoWeek":"31"}
const related = {
  date: {
    isoYear: '2021',
    isoWeek: '31',
  },
};
const now = moment();
console.log(now.clone().isoWeek(Number(related.date.isoWeek)).startOf('isoWeek'));
<script src="https://cdn.jsdelivr.net/npm/moment@2.29.1/moment.min.js"></script>

从对象中获得 isoYear 并添加 isoWeek 周后,您可以使用 startOf('isoWeek')endOf('isoWeek')

let related = {"isoYear":"2021","isoWeek":"31"};

console.log(moment(related.isoYear, 'YYYY').add(parseInt(related.isoWeek), 'weeks').startOf('isoWeek').format('DD/MM/YYYY'))

console.log(moment(related.isoYear, 'YYYY').add(parseInt(related.isoWeek), 'weeks').endOf('isoWeek').format('DD/MM/YYYY'))

console.log(moment(related.isoYear, 'YYYY').add(parseInt(related.isoWeek), 'weeks').startOf('month').format('DD/MM/YYYY'))

console.log(moment(related.isoYear, 'YYYY').add(parseInt(related.isoWeek), 'weeks').endOf('month').format('DD/MM/YYYY'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>

编辑

现在如果你想从 month 属性 得到月份,你可以这样做:

let related = {"isoYear":"2021","isoWeek":"31", "month": "06"}

console.log(moment(related.isoYear, 'YYYY').add(parseInt(related.month) - 1, 'months').startOf('month').format('DD/MM/YYYY'))

console.log(moment(related.isoYear, 'YYYY').add(parseInt(related.month) - 1, 'months').endOf('month').format('DD/MM/YYYY'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>

注意 add 函数上的 -1:这是因为在 moment 个月中数字从 0(一月)开始。