本文介绍了如何将一个周数转换为JavaScript中的日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图找到一些工作,但我没有运气。任何想法?示例:
2001年1月1日=> 2001-01-01
2007年26月26日=> 2007-06-01
解决方案
可能仍然对更包含的版本感兴趣:
功能firstDayOfWeek(年,周){
//年份1月1日
var d = new Date(year,0,1),
offset = d.getTimezoneOffset();
// ISO:第1周是今年第一个星期四的
//最近周四:当前日期+ 4 - 当前日数
//星期日从0到7
d.setDate(d.getDate()+ 4 - (d.getDay()|| 7));
// 7天*(周 - 第一周重叠)
d.setTime(d.getTime()+ 7 * 24 * 60 * 60 * 1000
*(周+(year == d.getFullYear()?-1:0)));
// daylight saving fix
d.setTime(d.getTime()
+(d.getTimezoneOffset() - offset)* 60 * 1000);
//返回星期一(星期四)
d.setDate(d.getDate() - 3);
return d;
}
I had tried to find some work done but I haven't had luck. Any ideas?
Examples:
Week, 1, 2001 => 2001-01-01
Week, 26, 2007 => 2007-06-01
解决方案
Someone might be still interested in a more contained version:
function firstDayOfWeek (year, week) {
// Jan 1 of 'year'
var d = new Date(year, 0, 1),
offset = d.getTimezoneOffset();
// ISO: week 1 is the one with the year's first Thursday
// so nearest Thursday: current date + 4 - current day number
// Sunday is converted from 0 to 7
d.setDate(d.getDate() + 4 - (d.getDay() || 7));
// 7 days * (week - overlapping first week)
d.setTime(d.getTime() + 7 * 24 * 60 * 60 * 1000
* (week + (year == d.getFullYear() ? -1 : 0 )));
// daylight savings fix
d.setTime(d.getTime()
+ (d.getTimezoneOffset() - offset) * 60 * 1000);
// back to Monday (from Thursday)
d.setDate(d.getDate() - 3);
return d;
}
这篇关于如何将一个周数转换为JavaScript中的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!