javascript 如何从周数和年份中获取一周的第一个日期和最后一个日期?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8803151/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 04:37:34  来源:igfitidea点击:

How to get first date and last date of the week from week number and year?

javascriptjquery

提问by balaphp

In JavaScript I want to get first date of the week and last date of the week by week number and year only.

在 JavaScript 中,我只想按周数和年份获取一周的第一个日期和一周的最后一个日期。

For example if I my input is:

例如,如果我的输入是:

2(week),2012

2(week),2012

Then my output should be:

那么我的输出应该是:

2012-01-08 and 2012-01-14

2012-01-08 and 2012-01-14

采纳答案by bardiir

Try this:

试试这个:

var year = 2012;
var week = 2;
var d = new Date("Jan 01, " + year + " 01:00:00");
var w = d.getTime() + 604800000 * (week - 1);
var n1 = new Date(w);
var n2 = new Date(w + 518400000)

console.log(n1);
console.log(n2);

n1 contains the first day of the week
n2 contains the last day of the week

n1 包含一周的第一天
n2 包含一周的最后一天

As for the constants:
604800000 is one week in milliseconds
518400000 is six days

至于常数:
604800000 是以毫秒为单位的一周
518400000 是六天

回答by Xig480

A little change to @bardiir 's answer, if the first day of the year is not Sunday(or Monday) that result is not correct. You should minus the number of the first day.

对@bardiir 的回答稍作改动,如果一年中的第一天不是星期日(或星期一),则结果不正确。你应该减去第一天的数量。

Changed code

更改代码

firstDay = new Date(2015, 0, 1).getDay();
console.log(firstDay);
var year = 2015;
var week = 67;
var d = new Date("Jan 01, " + year + " 01:00:00");
var w = d.getTime() - (3600000 * 24 * (firstDay - 1)) + 604800000 * (week - 1)
var n1 = new Date(w);
var n2 = new Date(w + 518400000)

console.log(n1);
console.log(n2);

if you wish the first is Sunday, change the (firstDay-1) to

如果您希望第一个是星期日,请将 (firstDay-1) 更改为

回答by Chandresh M

you can check and try with below link.

您可以使用以下链接检查并尝试。

How to get first and last day of the week in JavaScript

如何在 JavaScript 中获取一周的第一天和最后一天

It will may helpful to you.

它可能对你有帮助。

Thanks.

谢谢。

回答by perumalsamy

   dt = new Date();
   var firstDateOfWeek=(dt.setDate(dt.getDate()-dt.getDay()));
   var lastDateOfWeek=(dt.setDate(dt.getDate()+6-dt.getDay()));