有没有办法在javascript中创建一个日期对象使用年& ISO周数?
问题描述:
我正在尝试创建一个谷歌注释时间轴为此,我需要输入事件的日期。我唯一的信息是年份&事件的ISO周号。有没有办法在Javascript中创建一个Date对象,只需要一年&周数?我google了,但没有遇到任何可行的解决方案。
I am trying to create a google annotated timeline viz. For that I need to input the date of the event. The only information I have is the year & the ISO week number for the event. Is there a way in Javascript to create a Date object using just the year & week number? I googled it but did not come across any feasible solution.
感谢您的帮助!
答
如果1月1日在星期一,星期二,星期三或星期四,则是在01周。
如果1月1日在星期五,星期六或星期日,这是在前一年的52周或53周。
If 1 January is on a Monday, Tuesday, Wednesday or Thursday, it is in week 01. If 1 January is on a Friday, Saturday or Sunday, it is in week 52 or 53 of the previous year
Date.weekofYear= function(s){
var yw= s.split(/\D+0?/),
weeks= 7*yw[1]-7,
date1= new Date(yw[0], 0, 1),
day1= date1.getDay(),
incr= (day1> 0 && day1<5)? -1: 1;
if(yw[2]) weeks+= (+yw[2])-1;// optional day in week
while(date1.getDay()!= 1){
date1.setDate(date1.getDate()+incr);
}
date1.setDate(date1.getDate()+weeks);
return date1;
}
Date.weekofYear('2010-20').toLocaleDateString()
// (use UTC methods to start the weeks on Greenwich instead of local time)
/* returned value: (String)
Monday, May 17, 2010
*/