[英]Getting first date in week given a year,weeknumber and day number in javascript
Following is the code that calculates the week date, 以下是计算周日期的代码,
//Gets the week dayNumber date against the year,week number
var getWeekDate = function (year, weekNumber, dayNumber) {
var date = new Date(year, 0, 10, 0, 0, 0),
day = new Date(year, 0, 4, 0, 0, 0),
month = day.getTime() - date.getDay() * 86400000;
return new Date(month + ((weekNumber - 1) * 7 + dayNumber) * 86400000);
};
The code is working fine if I give the following values, 如果我给出以下值,代码工作正常,
Input: 输入:
year = 2012 年= 2012年
weekNumber = 1 weekNumber = 1
dayNumber = 0 //My week starts from monday, so I am giving it 0. dayNumber = 0 //我的星期从星期一开始,所以我给它0。
Output: 输出:
2nd,Jan 2012 //That's correct. 2012年1月2日//这是正确的。
Input: 输入:
year = 2013 年= 2013年
weekNumber = 1 weekNumber = 1
dayNumber = 0 //My week starts from monday, so I am giving it 0. dayNumber = 0 //我的星期从星期一开始,所以我给它0。
Output: 输出:
31st,DEC 2012 //That's in-correct. 2012年12月31日//这是正确的。
The first week of 2013 will start from 7th, Jan 2013 ieMonday but the above code is not calculating it correctly. 2013年的第一周将从2013年1月7日ieMonday开始,但上面的代码没有正确计算。
That's actually accurate because day zero (Monday) of week 1 of 2013 is still part of 2012. You could use a conditional to check whether the requested day of that week is part of the year. 这实际上是准确的,因为2013年第1周的第0天(星期一)仍然是2012年的一部分。您可以使用条件来检查该周的请求日是否属于该年的一部分。
//Gets the week dayNumber date against the year,week number
var getWeekDate = function (year, weekNumber, dayNumber) {
var date = new Date(year, 0, 10, 0, 0, 0),
day = new Date(year, 0, 4, 0, 0, 0),
month = day.getTime() - date.getDay() * 86400000,
ans = new Date(month + ((weekNumber - 1) * 7 + dayNumber) * 86400000);
if (weekNumber === 1 && ans.getMonth() !== 0) {
// We're still in last year... handle appropriately
}
return ans;
};
As an aside, it wouldn't be a bad idea to put some variable checking in place. 顺便说一句,将一些变量检查放在适当位置并不是一个坏主意。 I can input week 0, week 55, and day 92 without any issues.
我可以输入第0周,第55周和第92天,没有任何问题。 Obviously the results are still accurate, but they may issue confusing results to those thinking in terms of calendars.
显然结果仍然准确,但它们可能会给那些在日历方面思考的人带来令人困惑的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.