如何计算给定日期的星期数?

如果我有日期,该如何计算该年中该日期的星期数?


例如,在2008年,第1周是1月1日至1月6日,第2周是1月7日至13日,因此,如果我的日期是2008年1月10日,那么我的周数将是2。


一种算法非常适合我入门,示例代码也将有所帮助-我正在Windows上使用C ++进行开发。


猛跑小猪
浏览 753回答 3
3回答

慕莱坞森

伪代码:int julian = getDayOfYear(myDate)&nbsp; // Jan 1 = 1, Jan 2 = 2, etc...int dow = getDayOfWeek(myDate)&nbsp; &nbsp; &nbsp;// Sun = 0, Mon = 1, etc...int dowJan1 = getDayOfWeek("1/1/" + thisYear)&nbsp; &nbsp;// find out first of year's day// int badWeekNum = (julian / 7) + 1&nbsp; // Get our week# (wrong!&nbsp; Don't use this)int weekNum = ((julian + 6) / 7)&nbsp; &nbsp;// probably better.&nbsp; CHECK THIS LINE. (See comments.)if (dow < dowJan1)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// adjust for being after Saturday of week #1&nbsp; &nbsp; ++weekNum;return (weekNum)为了明确起见,此算法假定您按如下方式计算周数:S&nbsp; M&nbsp; T&nbsp; W&nbsp; R&nbsp; F&nbsp; S&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 1&nbsp; 2&nbsp; 3&nbsp; &nbsp; <-- week #14&nbsp; 5&nbsp; 6&nbsp; 7&nbsp; 8&nbsp; 9 10&nbsp; &nbsp; <-- week #2[etc.]getDayOfWeek()和getDayOfYear()是大多数语言中的标准日期对象操作。如果您没有它们,可以在查明星期几之后,从某个已知的日期算起(1970年1月1日是常见的日期)。如果要实现自己的日期计数例程,请记住,可以被100整除的年份不是 leap年,除非它们也可以被400整除。因此1900不是year年,而2000是leap年。如果您要回到较早的时间工作,则必须弄乱公历日历和朱利安日历等,请参阅Wikipedia上的大量信息。该链接更详细地讨论了Windows / C ++中的日期/时间功能。
打开App,查看更多内容
随时随地看视频慕课网APP