怎样用JavaScript列出一年中所有星期天的日期( 二 )

#include "stdio.h"#define BASE_YEAR 1970/* Unix */#define BASE_MONTH 0/* Jan */#define BASE_DATE 0/* Jan 1st */#define BASE_WEEK 4/* THU, 0 for SUN */int main(){\tint monthArray = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};\tint year = 2016; /* Change it to 2015 if you want 2015 */\tif ((year % 4 == 0 \u0026amp;\u0026amp; year % 100 != 0) || (year % 400 == 0))\t{\t\tmonthArray += 1;\t}\tint yearPassed = year - BASE_YEAR;\tint dayPassed = 365 * yearPassed + (yearPassed - 2) / 4 \t\t+ (yearPassed - 2) / 400\t\t- (yearPassed - 2) / 100;\tint dayOfThisYear = 0;\tint currentMonth = 0;\tfor(currentMonth = 0; currentMonth \u0026lt; 12; ++currentMonth)\t{\t\tint currentMonthDayNum = monthArray;\t\tint monthDay = 0;\t\tfor(monthDay = 0; monthDay \u0026lt; currentMonthDayNum; ++monthDay)\t\t{\t\t\tdayOfThisYear++;\t\t\tint weekDay = (dayOfThisYear + dayPassed + BASE_WEEK) % 7; \t\t\tif (weekDay == 0)/* change to 1 for SUN, but I don\u0026#39;t know why! */\t\t\t{\t\t\t\tprintf("SUN :\\t%d, %d\", currentMonth + 1, monthDay + 1);\t\t\t}\t\t}\t}}
■网友
谢邀。手机答。首先 d= new Date();然后设置日期和时分秒为一年的开始。然后 d.getTime()就是一年开始的时间戳。这个时候判断d的星期是不是周日,如果不是,d.setTime( d.getTime() + 86400000 ) 再判断,直到d的星期是周日。 其中86400000是一整天的毫秒。接下来就简单了,循环往d上面加7天的毫秒数,然后显示日期。
■网友
var bigMonths = , smallMonths = , days_31 = 31, days_30 = 30, days_28 = 28, days_29 = 29;function leapYear(year) { return !(year % (year % 100 ? 4 : 400));}function getDaysInMonth(m,year){ var month; if (bigMonths.indexOf(m)!=-1){ month=days_31; }else if (smallMonths.indexOf(m)!=-1){ month=days_30; }else { if (leapYear(year)){ month=days_29; }else{ month=days_28; } } return month;}function getSundayOfYear(year){ var days,sundays = ; for (var m = 1;m\u0026lt;=12;m++){ days = getDaysInMonth(m,year); for (var i= 1;i\u0026lt;=days;i++){ var date = new Date(year+"/"+m+"/"+i); if (date.getDay() === 0){ sundays.push(date); } } } return sundays;}console.log(getSundayOfYear(2016));
■网友
function sundays(year) { var arSundays = ; for (var date = new Date(year, 0, 1), day = date.getDay(), _ = day \u0026amp;\u0026amp; date.setDate(date.getDate() + 7 - day); date.getFullYear() === year; date.setDate(date.getDate() + 7)) { arSundays.push(date.toLocaleString()); } return arSundays;}console.time(\u0026#39;sundays1000\u0026#39;);for (var i = 0; i \u0026lt; 1000; i++) { sundays(2016);}console.timeEnd(\u0026#39;sundays1000\u0026#39;);sundays1000: 420.723ms代码简洁,效率一般


推荐阅读