JS gets the time of the first day and the last day of the week

Business scene

The author recently encountered a business scenario of "calculating the first and last day of the week"
. When seeing time-related problems, the first thing that comes to mind must be new Date()
but is there a faster and more convenient way to solve it? The author finally found a Day.js library and found it very useful. If you have a classmate with the same business scenario as me, you can try
Day.js

usage

Get the time of the first and last day of the week

1. npm installation

npm install dayjs --save

2. Introduce in the project

import dayjs from 'dayjs'

3. Logic

function getNowWeekTime() {
    
    
  let today = dayjs().format('YYYY-MM-DD')
  let today_week = dayjs().day()
  let start_time = dayjs(today)
    .subtract(today_week - 1, 'day')
    .format('YYYY.MM.DD')
  let end_time = dayjs(start_time).add(6, 'day').format('YYYY.MM.DD')
  let start_end_time = `${
     
     start_time}-${
     
     end_time}`
  let timeObj = {
    
    
    start_time: start_time,
    end_time: end_time,
    start_end_time: start_end_time,
  }
  return timeObj
}

result
insert image description here

Guess you like

Origin blog.csdn.net/m0_46627407/article/details/126822295