用ES6写的给定日期最近一天工作日

通过'http://tool.bitefu.net/jiari/?d=20210815获取最近一天工作日,此API反回0表示工作日,1表示周末,2表示假期

//workday.js

import fetch from 'node-fetch'

const URL = 'http://tool.bitefu.net/jiari/?d=' // 日期格式  d=20210814

const fetchAsync = async (url, date) => {
  const response = await fetch(url + date)
  return await response.text()
}

function sleep(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms))
}

async function getLastWorkday(datetime = new Date(), delay = 1000) {
  let lastWorkday
  datetime.setDate(datetime.getDate() + 1)
  while (true) {
    lastWorkday = new Date(datetime.setDate(datetime.getDate() - 1))
      .toISOString()
      .split('T')[0]
      .split('-')
      .join('')
    const isWorkDay = await fetchAsync(URL, lastWorkday)
    if (isWorkDay === '0') {
      break
    }
    await sleep(delay)
  }

  return [lastWorkday, datetime]
}

用法

import getLastWorkday from './workday.js'

const lastWorkday = async () => {
  let result = await getLastWorkday(new Date('2021-08-01'))
  console.log(result)
  return result
}

lastWorkday()

posted @ 2021-08-15 10:16  joe62  阅读(148)  评论(0编辑  收藏  举报