Remember a bug encountered when using momentjs to get the start time of all weeks in a year

Time:2020-9-19

preface

The business needs to generate a drop-down list after selecting a year, so that users can select each week of the year, and then the front-end generates the start and end time of the week (Monday morning)00:00:00By Sunday night00:00:00)To the back-end interface to get the data of the selected week.

operation

For the convenience of development, themomentjs

The following is what we did at the beginning. The result of this kind of employment is problematic:

//Figure out how many weeks there are in a year and return the start and end times for each
export const mapWeeksOfyear = ({ year, week } = {}) => {
    const nowYear = year ? year : moment().year();
  
        //Set the year being processed
    let handleYear = moment(new Date(String(nowYear)));
      //How many weeks are there in this year
    const totalWeeks = handleYear.endOf('year').isoWeek();
    const arr  = [];
    for(let i = 1;i <= totalWeeks;i++){
        arr.push({
            value: i,
            Name: 'week' + I +'week ',
            startTime:  handleYear.week (i) . startOf ('week '). Valueof(), // start time of the week
            endTime:  handleYear.week (i) . endof ('week '). Valueof(), // end of the week
        })
    } 
    return arr
}

For the above results, I tested the values of the first few weeks without any problem, but later found that in the later weeks, the start and end times did not match seriously, and there was always an extra year.

For a long timemomentjsOfAPIAfter I didn’t find out the reason, I decided to write a method myself. In fact, this is not difficult. Of course, I can’t rule out the above methodmomentjsOfAPIIncorrect understanding

Rewrite with native JS

/**
*Figure out how many weeks there are in a year and return the start and end times for each
* 
*/
const mapWeeksOfyear = ({ year, week } = {}) => {
  const handleYear = year ? year : new Date().getFullYear()
  //The start and end of the year
  const yearBegin = new Date(`${handleYear}/01/01 00:00:00`)
  const yearEnd = new Date(`${handleYear}/12/31 00:00:00`)
  const aDay = 24 * 60 * 60 * 1000
  const aWeek = aDay * 7

  const beginTime = handleDay(yearBegin, aDay)
  const arr  = getWeek(beginTime, yearEnd.getTime(), aWeek) 
  return arr
}
function getWeek (beginTime, endTime, aWeek) {
  const arr = []
  
  for(let i = beginTime; i <= endTime; i += aWeek) {
    let time = new Date(i)
    arr.push({
      startTime: i,
      endTime: i + aWeek,
      s: `${ time.getFullYear ()} ${ time.getMonth () + 1} ${ time.getDate ()} weeks${ time.getDay () + 1} `
    })
  }
  arr.forEach((item, i) => {
    let index = i + 1
    item.value = index
    item.name  ='week' + index + '
  })
  console.log(arr)
  return arr
}
/**
 *Of course, the Monday of the first week of the year is not necessarily on January 1. It may include the last few days of December of the previous year
 *The default first week may include the last days of December of the previous year
*/
function handleDay (yearBegin, aDay) {
    let time, 
      day = yearBegin.getDay()
    switch(day){
        case 0:
            time = 0;
            break;
        case 1: 
            time = 1 * aDay;
            break;
        case 2: 
            time = 2 * aDay;
            break;
        case 3: 
            time = 3 * aDay;
            break;
        case 4: 
            time = 4 * aDay;
            break;
        case 5: 
            time = 5 * aDay;
            break;
        case 6: 
            time = 6 * aDay;
            break;
        default: 
            time = 0;
            break;
    }
    return yearBegin.getTime() - time
}

At this point, the above obtains all the weeks of the year, including the start and end times of the current week

results of enforcement

Remember a bug encountered when using momentjs to get the start time of all weeks in a year

Recommended Today

Java security framework

The article is mainly divided into three parts1. The architecture and core components of spring security are as follows: (1) authentication; (2) authority interception; (3) database management; (4) authority caching; (5) custom decision making; and;2. To build and use the environment, the current popular spring boot is used to build the environment, and the actual […]