简体   繁体   English

React 从给定月份获取日历周数

[英]React Get Calendar Week Numbers from given month

may someone can help me.可能有人可以帮助我。 I need to calculate the week numbers in a given month.我需要计算给定月份的周数。 Example the month july should have week number 26, 27, 28, 29 and 30. How do I calculate this and put them all into an array?例如,7 月应该有第 26、27、28、29 和 30 周。如何计算并将它们全部放入数组中? Till now I only get the current calendar week number.到目前为止,我只得到当前日历周数。

  const currentWeekNumber = useMemo(() => {
    const currentDate = new Date();
    const startDate = new Date(currentDate.getFullYear(), 0, 1);
    const days = Math.floor((currentDate.getTime() - startDate.getTime()) / (24 * 60 * 60 * 1000));

    const weekNumber = Math.ceil(days / 7);
    return weekNumber;
  }, []);

you can get the first day and last day of the current month and do the same process.您可以获取当月的第一天和最后一天并执行相同的过程。

const range = (x,y) => {
  let array = [];
  for(let i = x; i<y; i++){
    array.push(i);
  }
  return array;
} 
 
const currentDate = new Date();
const startDate = new Date(currentDate.getFullYear(), 0, 1);

const firstDayOfMonth = new Date(currentDate.getFullYear(), currentDate.getMonth(),1);
const lastDayOfMonth = new Date(currentDate.getFullYear(), currentDate.getMonth()+1);

const difFirstDayOfMonth = Math.floor((firstDayOfMonth.getTime() - startDate.getTime()) / (24 * 60 * 60 * 1000) );
const difLastDayOfMonth = Math.floor((lastDayOfMonth.getTime() - startDate.getTime()) / (24 * 60 * 60 * 1000) );

const firstWeek = Math.ceil(difFirstDayOfMonth / 7);
const lastWeek = Math.ceil(difLastDayOfMonth / 7);

const rangeOfWeeks = range(firstWeek, lastWeek);

After that, you create an array from the week number of the first day of the month until the week number of the last day of the current month (range function).之后,您创建一个从当月第一天的周数到当月最后一天的周数的数组(范围函数)。

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

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