最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to determine which date is on friday? - Stack Overflow

programmeradmin1浏览0评论

I have two dropdownlists - one for year and one for weeks. How to determine the chosen weeks date should be the friday. So for example I chose week 34 and year 2011 then I should know the date on friday, in format like this: 2011-08-23. And preferably in javascript too.

I have two dropdownlists - one for year and one for weeks. How to determine the chosen weeks date should be the friday. So for example I chose week 34 and year 2011 then I should know the date on friday, in format like this: 2011-08-23. And preferably in javascript too.

Share Improve this question asked Apr 6, 2010 at 12:02 poopoo 1,1154 gold badges13 silver badges21 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 8

Use date.js. It is quite handy for any date-related Javascripting.

Examples from their site:

// 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');

Given a recent version (from SVN) of date.js, the following will give you what you seek.

function date_of_friday(year, week) {
    return Date.parse(year + "-01-01").setWeek(week).next().friday();
}

As shown below, this gives the correct answer for your example as well as for the case when the first day of the year is in week number 1 and the case when it is not (week number 1 is the week containing the first Thursday of the year, according to ISO 8601).

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)

You can also use a smaller 'library':

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*/
发布评论

评论列表(0)

  1. 暂无评论