![](/img/trans.png)
[英]Refresh a page(1st page) from another page (3rd page) using javascript
[英]Using moment to round to next 1st or 3rd Monday
想知道是否有人可以提供帮助,我正在尝试使用 moment.js 进行约会(例如今天),然后使用它返回下一个或第三个星期一,以较早者为准。
因此,例如今天是 01/18,下一个(第 1 个或第 3 个,在这种情况下,第 3 个星期一将是 1/20)。
或者,如果今天是下一个 1/27(在这种情况下第一个星期一是 2/03)。
一种算法是:
没有库的实现是:
/* Get next 1st or 3rd Monday of month ** @param {Date} date : start date ** @returns {Date} date for 1st or 3rd Monday of month */ function getMonday(date) { // Copy date so don't affect original date = new Date(date); // If not Monday, move to next if (date.getDay() != 1) { date.setDate(date.getDate() + 8 - (date.getDay() || 7)) } let day = date.getDate(); // If after 1st Monday, move to 3rd if (day > 7 && day < 14) { date.setDate(date.getDate() + 7); // If after 3rd Monday, move to 1st of next month } else if (day > 21) { date.setMonth(date.getMonth() + 1, 1); date = getMonday(date); } return date; } // Test in March 2020 let d = new Date(2020,2,1); let opts = {weekday:'short', day:'2-digit', month:'short'}; for (var i=0; i<31; i++) { console.log(d.toLocaleString('en-gb', opts) + ' -> ' + getMonday(new Date(d)).toLocaleString('en-gb', opts)); d.setDate(d.getDate() + 1); }
下面是使用 moment.js 的实现。 使用moment.endOf('week')
很诱人,但由于它是“区域设置感知”,它可能会在星期六或星期日结束,具体取决于主机系统设置,因此逻辑最终与普通 js 解决方案相同,仅使用 moment.js 方法:
/* @param {Moment} m - moment object for start date ** @returns {Moment} moment object for required Monday */ function getMondayMoment(m) { m = moment(m); // If not Monday, move to next if (m.day() != 1) { m.add(8 - (m.day() || 7), 'days'); } let day = m.date(); // If after 1st Monday, move to 3rd if (day > 7 && day < 14) { m.add(7, 'days'); // If after 3rd Monday, move to 1st of next month } else if (day > 21) { m.set({month: m.get('month') + 1, date: 1}); m = getMondayMoment(m); } return m; } // Test over March 2020 let m = moment('2020-03-01'); for (var i=0; i<31; i++) { console.log( m.format('ddd DD MMM') + ' -> ' + getMondayMoment(m).format('ddd DD MMM') ); m.add(1, 'day'); }
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.