简体   繁体   English

从 moment.js 获取一个月内的周数(行)

[英]get the number of weeks (rows) in a month from moment.js

I'd like to get the number of calendar rows (weeks) in any month using momentjs我想使用momentjs获取任何月份的日历行数(周数)

For example:例如:

This would be 5这将是5

在此处输入图像描述

and this would be 6这将是6

在此处输入图像描述

Heres what I have to work with:这是我必须使用的:

I have the month, start of month, and end of month as a moment items我有月份、月初和月底作为时刻项目

const month; // (month moment obj)
const start = moment(month).startOf('month');
const end = moment(month).endOf('month');

Heres what I've tried so far (with no luck)这是我迄今为止尝试过的(没有运气)

const weeks = end.diff(start, 'week'); // always gives 4
const weeks = moment.duration(end - start).weeks() + 1; // always gives 5

I really would prefer to use Moment.js for simplicity and accuracy.为了简单和准确,我真的更喜欢使用 Moment.js。 I've seen some pure JS answers on here but none of them are truly reliable.我在这里看到了一些纯 JS 的答案,但没有一个是真正可靠的。

This is a curious problem.这是一个奇怪的问题。 Edited new solution: count the days of the first week (row one), then the next weeks (middle rows), if there are pending days add another row:编辑后的新解决方案:计算第一周的天数(第一行),然后计算接下来的几周(中间行),如果有待处理的天数,则添加另一行:

Taking into account that week starts on Monday with 'isoWeekDay()'.考虑到该周从星期一开始,使用“isoWeekDay()”。

As of October 9th 2019:截至 2019 年 10 月 9 日:

let now = moment('9/oct/2019');
// First row
let firstWeekDays = 7 - now.startOf('month').isoWeekday() + 1;
let rows = 1
rest = now.daysInMonth() - firstWeekDays;
// Middle rows
let middleRows = Math.floor(rest/7);
rows = rows + middleRows;
rest = rest - (middleRows * 7);
// Last row?
if (rest > 0) {
    rows = rows + 1;
}
console.log(rows); // 5

You should take in consideration also the offsets.您还应该考虑偏移量。


function weeksOfMonth (input = moment()) {
  const startMonth = input.clone().startOf('month');
  const startWeek = startMonth.clone().startOf('isoWeek');
  const startOffset = startMonth.diff(startWeek, 'days'); 
  
  const endMonth = input.clone().endOf('month');
  const endWeek = endMonth.clone().endOf('isoWeek');
  const endOffset = endWeek.diff(endMonth, 'days'); 

  return Math.ceil((endMonth.diff(startMonth, 'days') + startOffset + endOffset) / 7);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM