我有两个下拉列表 - 一年一次,一周一周。如何确定所选的周日期应该是星期五。例如,我选择了第34周和2011年,那么我应该知道星期五的日期,格式如下:2011-08-23。 最好也是在javascript中。
答案 0 :(得分:7)
使用date.js。对任何与日期相关的Javascripting都非常方便。
他们网站的例子:
// What date is next thrusday?
Date.today().next().thursday();
// Add 3 days to Today
Date.today().add(3).days();
// Is today Friday?
Date.today().is().friday();
// Number fun
(3).days().ago();
// 6 months from now
var n = 6;
n.months().fromNow();
// Set to 8:30 AM on the 15th day of the month
Date.today().set({ day: 15, hour: 8, minute: 30 });
// Convert text into Date
Date.parse('today');
Date.parse('t + 5 d'); // today + 5 days
Date.parse('next thursday');
Date.parse('February 20th 1973');
Date.parse('Thu, 1 July 2004 22:30:00');
答案 1 :(得分:1)
鉴于date.js的最新版本(来自SVN),以下内容将为您提供所需内容。
function date_of_friday(year, week) {
return Date.parse(year + "-01-01").setWeek(week).next().friday();
}
如下图所示,这给出了您的示例的正确答案,以及一年中第一天是第1周的情况以及不是第1周的情况(第1周是包含第一周的情况)根据{{3}}),今年的星期四。
date_of_friday(2011, 34); // Fri Aug 26 2011 00:00:00 GMT+0200 (CET)
date_of_friday(2011, 1); // Fri Jan 07 2011 00:00:00 GMT+0100 (CET)
date_of_friday(2013, 1); // Fri Jan 04 2013 00:00:00 GMT+0100 (CET)
答案 2 :(得分:0)
您还可以使用较小的“图书馆”:
Date.fromWeek= function(nth, y, wkday){
y= y || new Date().getFullYear();
var d1= new Date(y, 0, 4);
if(wkday== undefined) wkday= 1;
return d1.nextweek(wkday, nth);
}
Date.prototype.nextweek= function(wd, nth){
if(nth== undefined) nth= 1;
var incr= nth < 0? 1: -1,
D= new Date(this), dd= D.getDay();
if(wd== undefined) wd= dd;
while(D.getDay()!= wd) D.setDate(D.getDate()+ incr);
D.setDate(D.getDate()+ 7*nth);
return D;
}
// test case
var dx= Date.fromWeek(34, 2011, 5);
alert([dx.getFullYear(), dx.getMonth()+1, dx.getDate()].join('-'));
/*returned value: (String) 2011-8-26*/