問題描述
如果我有一個日期,我如何計算該日期在那一年中的周數(shù)?
If I have a date, how do I calculate the week number for that date within that year?
例如,在 2008 年,1 月 1 日至 1 月 6 日在第 1 周,而 1 月 7 日至 13 日在第 2 周,因此如果我的日期是 2008 年 1 月 10 日,則我的周數(shù)為 2.
For example, in 2008, January 1st to January 6th are in week 1 and January 7th to the 13th are in week 2, so if my date was January 10th 2008, my week number would be 2.
算法非常適合讓我入門,示例代碼也會有所幫助 - 我正在 Windows 上使用 C++ 進(jìn)行開發(fā).
An algorithm would be great to get me started and sample code would also help - I'm developing in C++ on Windows.
從日期中獲取周數(shù)MS SQL Server 2005?
推薦答案
偽代碼:
int julian = getDayOfYear(myDate) // Jan 1 = 1, Jan 2 = 2, etc...
int dow = getDayOfWeek(myDate) // Sun = 0, Mon = 1, etc...
int dowJan1 = getDayOfWeek("1/1/" + thisYear) // find out first of year's day
// int badWeekNum = (julian / 7) + 1 // Get our week# (wrong! Don't use this)
int weekNum = ((julian + 6) / 7) // probably better. CHECK THIS LINE. (See comments.)
if (dow < dowJan1) // adjust for being after Saturday of week #1
++weekNum;
return (weekNum)
澄清一下,這個算法假設(shè)你像這樣計算你的周數(shù):
To clarify, this algorithm assumes you number your weeks like this:
S M T W R F S
1 2 3 <-- week #1
4 5 6 7 8 9 10 <-- week #2
[etc.]
getDayOfWeek() 和 getDayOfYear() 是大多數(shù)語言中的標(biāo)準(zhǔn)日期對象操作.如果您的沒有它們,您可以從某個已知日期(1970 年 1 月 1 日是常見的日期)開始計算,然后查看一周中的哪一天.
getDayOfWeek() and getDayOfYear() are standard date-object operations in most languages. If yours doesn't have them, you can count-forward from some known date (Jan 1, 1970 is a common one), after looking up to see what day of the week it was.
如果您要實現(xiàn)自己的日期計數(shù)例程,請記住可被 100 整除的年份是不是閏年,除非它們也可被 400 整除.因此 1900 不是閏年年,但 2000 年是.如果您要回到過去工作很長時間,則必須弄亂公歷與儒略歷等,請參閱 維基百科提供大量相關(guān)信息.
If you're going to implement your own date counting routines, remember that years that are divisible by 100 are NOT leap years, unless they are also divisible by 400. So 1900 was not a leap year, but 2000 was. If you're going to work far back in time, you have to mess with Gregorian vs Julian calendars, etc., see Wikipedia for loads of info on that.
此鏈接 更詳細(xì)地討論了 Windows/C++ 中的日期/時間函數(shù)細(xì)節(jié).
This link talks about date/time functions in Windows/C++ in greater detail.
這篇關(guān)于如何計算給定日期的周數(shù)?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!