gpt4 book ai didi

javascript - 获取第 N 周第 X 天的日期

转载 作者:行者123 更新时间:2023-12-01 01:31:49 27 4
gpt4 key购买 nike

我有一个看起来像这样的对象:

const availability = {
week1: {
mon: false,
tue: true,
wed: true,
thu: true,
fri: false,
},
week2: {
mon: false,
tue: true,
wed: true,
thu: true,
fri: false,
},
week3: {
mon: false,
tue: true,
wed: true,
thu: true,
fri: false,
},
week4: {
mon: false,
tue: true,
wed: true,
thu: true,
fri: false,
},
};

这显示某人在当月第一、第二……周有空。

我现在需要的是每一天的真实日期。例如本月第一周的星期二日期、该月第二周的星期二日期等等。

我已经检查了 date-fns 和 moment.js,但我不知道如何解决这个问题。

最佳答案

如果我们假设要求是从该月的第一个星期一开始,那么您可以将该月分成几周,并使用您的可用性来映射它们。我用的是官方的moment-range插件在这里,但您可以通过其他方式计算这些范围:

const Moment = require('moment');
const MomentRange = require('moment-range');
const moment = MomentRange.extendMoment(Moment);

const availability = { week1: { mon: false, tue: true, wed: true, thu: true, fri: false, }, week2: { mon: false, tue: true, wed: true, thu: true, fri: false, }, week3: { mon: false, tue: true, wed: true, thu: true, fri: false, }, week4: { mon: false, tue: true, wed: true, thu: true, fri: false, }, };

const calcDays = (data, days) => {
// get the assumed first Monday of the current month
let fM = moment().startOf('month').isoWeekday('Monday')
let cM = moment().month()

// get the actual first Monday
fM = fM.month() < cM ? fM.add(1, 'week').isoWeekday('Monday') : fM.month() > cM ? fM.subtract(1, 'week').isoWeekday('Monday') : fM

// Calc the range based on first Monday and end of month
const range = moment.range(fM, moment().endOf('month'));
// Break into weeks
const weeks = [...Array.from(range.by('week')), moment().endOf('month')]

return Object.values(availability).reduce((r,c,i) => {
var weekRanges = Array.from(moment.range(weeks[i], weeks[i + 1]).by('day'))
Object.entries(c).map(([k, v], j) => v ? r.push(weekRanges[j].format()) : v)
return r
}, [])
}

console.log(calcDays(availability))

输出(2018 年 11 月 8 日运行):

[ '2018-11-06T00:00:00+00:00',
'2018-11-07T00:00:00+00:00',
'2018-11-08T00:00:00+00:00',
'2018-11-13T00:00:00+00:00',
'2018-11-14T00:00:00+00:00',
'2018-11-15T00:00:00+00:00',
'2018-11-20T00:00:00+00:00',
'2018-11-21T00:00:00+00:00',
'2018-11-22T00:00:00+00:00',
'2018-11-27T00:00:00+00:00',
'2018-11-28T00:00:00+00:00',
'2018-11-29T00:00:00+00:00' ]

可以看到working here

关于javascript - 获取第 N 周第 X 天的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53211862/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com