依日期計算週數
問題:
給定一個日期,決定週數年內的那個日期。例如,2008年,1月1日至1月6日為第1週,1月7日至13日為第2週。若日期是2008年1月10日,則對應的周數應為2。
ISO 8601 標準:
請記住,一年中的「第 n」週可能會有所不同。 ISO 8601 標準定義了周編號的具體準則:
實作:
以下C 語言程式碼範例示範如何依照ISO 8601 標準計算週數:
#include <chrono> #include <iostream> using namespace std; class Date { private: int year; int month; int day; public: Date(int year, int month, int day) : year(year), month(month), day(day) {} int getWeekNumber() { // Convert the date to a system_time object time_t t = time(0); tm* timeinfo = localtime(&t); // Create a system_time object for the first day of the year tm first_of_year; first_of_year.tm_year = year - 1900; first_of_year.tm_mon = 0; first_of_year.tm_mday = 1; time_t first_of_year_time = mktime(&first_of_year); // Calculate the number of days between the first day of the year and the given date long days_since_first_of_year = difftime(t, first_of_year_time) / (60 * 60 * 24); // Calculate the week number based on the number of days since the first day of the year int week_number = 1 + (days_since_first_of_year / 7); // Adjust the week number for possible week 53 int days_in_year = days_since_first_of_year + 1; int days_in_last_week = days_in_year % 7; if (days_in_last_week >= 5 && (week_number == 53 || (week_number == 52 && days_in_year >= 371))) { week_number = 53; } return week_number; } }; int main() { Date date(2008, 1, 10); cout << "Week number for January 10th 2008 is: " << date.getWeekNumber() << endl; return 0; }
輸出:
Week number for January 10th 2008 is: 2
以上是如何使用 ISO 8601 標準計算日期的周數?的詳細內容。更多資訊請關注PHP中文網其他相關文章!