简体   繁体   English

获取一年中每个星期四的日期Javascript

[英]Get date for every Thursday in the year Javascript

Given a day of the week ( var day ) the code below will print the date of each day in the year starting from today. 给定星期几( var day ),下面的代码将从今天开始打印一年中每一天的日期。 Since 4 = Thursday, I will get a list of all the Thursdays left in the year. 由于4 =星期四,我将获得一年中所有剩余的星期四的列表。 I was just curious if there was some 'neater' way to accomplish this? 我只是好奇是否有某种“更整洁”的方式来做到这一点?

var day = 4;
var date = new Date();
var nextYear = date.getFullYear() + 1;

while(date.getDay() != day)
{
    date.setDate(date.getDate() + 1)    
}

while(date.getFullYear() < nextYear)
{
    var yyyy = date.getFullYear();

    var mm = (date.getMonth() + 1);
    mm = (mm < 10) ? '0' + mm : mm;

    var dd = date.getDate();
    dd = (dd < 10) ? '0' + dd : dd;

    console.log(yyyy + '-' + mm + '-' + dd)

    date.setDate(date.getDate() + 7);
}

Output: 输出:

2011-02-10 2011-02-10

2011-02-17 2011-02-17

2011-02-24 2011-02-24

2011-03-03 2011-03-03

2011-03-10 2011-03-10

..etc ..等等

Well, it would look a lot prettier if you used Datejs . 好吧,如果您使用Datejs ,它将看起来更漂亮。

var thursday = Date.today().next().thursday(),
    nextYear = Date.next().january().set({day: 1}),
    format = 'yyyy-MM-dd';

while (thursday.isBefore(nextYear))
{
    console.log(thursday.toString(format));
    thursday = thursday.add(7).days();
}

See also http://code.google.com/p/datejs/ . 另请参阅http://code.google.com/p/datejs/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM