写月报,用年月的格式即可。
写周报,需要用到年周的格式,
目前这个没法直接取到,有什么简单方法实现?
      请
      登录后发表观点
    


不只是周月报,年度,日报都有
用函数判断

您好,以下是使用 JavaScript 实现该功能的代码:
function getWeekNum(dateStr) {
  const date = new Date(dateStr)
  const year = date.getFullYear().toString().substr(2)
  const firstDay = new Date(date.getFullYear(), 0, 1)
  const dayOfWeek = firstDay.getDay()
  const initDiff = dayOfWeek > 0 ? 7 - dayOfWeek : 0
  firstDay.setDate(1 + initDiff)
  const days = Math.round((date.getTime() - firstDay.getTime()) / (24 * 60 * 60 * 1000))
  const weekNum = Math.floor((days + initDiff) / 7) + 1
  const weekStr = weekNum < 10 ? `0${weekNum}` : `${weekNum}`
  const startDate = formatDate(firstDay)
  const endDate = formatDate(new Date(firstDay.getTime() + 6 * 24 * 60 * 60 * 1000))
  return year + weekStr + ',' + startDate + '~' + endDate
}
function formatDate(date) {
  const year = date.getFullYear()
  const month = date.getMonth() + 1 < 10 ? `0${date.getMonth() + 1}` : `${date.getMonth() + 1}`
  const day = date.getDate() < 10 ? `0${date.getDate()}` : `${date.getDate()}`
  return `${year}-${month}-${day}`
}
// 示例
const dateStr = '2023-04-12'
const weekNum = getWeekNum(dateStr)
console.log(weekNum) // 输出: 2314,2023-04-11~2023-04-17
代码解释:
- getWeekNum函数接收一个日期字符串- dateStr,返回一个字符串,包括周别和开始日期、结束日期。
- 首先使用 new Date(dateStr)将输入的日期字符串转换成Date对象,然后获取当前年份的后两位。
- 根据计算公式推算出本年度第一周的开始日期 firstDay。
- 计算出输入日期 date是本年度的第几天,然后根据每周 7 天来确定它所处的周别weekNum。
- 返回格式化后的周别字符串。
- formatDate函数用于将日期对象转化为字符串。