在 JavaScript 中从周数计算日期 [英] Calculate date from week number in JavaScript

查看:19
本文介绍了在 JavaScript 中从周数计算日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在知道周数和年份的 JavaScript 中计算日期?对于第 20 周和 2013 年,我想获得 2013-05-16.我是这样尝试的:

How can I calculate the date in JavaScript knowing the week number and the year? For week number 20 and year 2013 I want to obtain 2013-05-16. I am trying it like this:

Date.prototype.dayofYear = function () {
  var d = new Date(this.getFullYear(), 0, 0)
  return Math.floor((/* enter code here */ this - d) / 8.64e + 7)
}

推荐答案

function getDateOfWeek(w, y) {
    var d = (1 + (w - 1) * 7); // 1st of January + 7 days for each week

    return new Date(y, 0, d);
}

这里使用简单周定义,意思是 2013 年的第 20 周是 5 月 14 日.

This uses the simple week definition, meaning the 20th week of 2013 is May 14.

要计算给定的ISO8601 周(这将始终是星期一)

To calculate the date of the start of a given ISO8601 week (which will always be a Monday)

function getDateOfISOWeek(w, y) {
    var simple = new Date(y, 0, 1 + (w - 1) * 7);
    var dow = simple.getDay();
    var ISOweekStart = simple;
    if (dow <= 4)
        ISOweekStart.setDate(simple.getDate() - simple.getDay() + 1);
    else
        ISOweekStart.setDate(simple.getDate() + 8 - simple.getDay());
    return ISOweekStart;
}

结果:2013年的第20周是5月13日,可以确认这里.

Result: the 20th week of 2013 is May 13, which can be confirmed here.

这篇关于在 JavaScript 中从周数计算日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆