計算給定日期的周數
在許多應用程式中,確定給定日期的周數至關重要。此資訊在規劃和調度等行業非常有用。本文探討了基於 ISO 8601 計算週數的演算法和程式碼範例。
ISO 8601 定義
ISO 8601 標準定義了基於ISO 8601 的周數遵循以下規則:
演算法
要計算週數,請執行以下操作這些步驟:
C 程式碼範例
#include <iostream> #include <chrono> using namespace std; // Date manipulation functions int getYear(tm* date); int getMonth(tm* date); int getDay(tm* date); int getWeek(tm* date); // Algorithm for calculating week number based on ISO 8601 int getWeek(tm* date) { // Calculate d1w1, the first day (Monday) of the first week (Week 1) of the year tm d1w1 = *date; d1w1.tm_mon = 0; // January (0-based month) d1w1.tm_mday = 1; // First day of the month d1w1.tm_wday = 1; // Monday (1-based day of the week) // Get the number of days between the given date and d1w1 time_t t1 = mktime(&d1w1); time_t t2 = mktime(date); int delta = int((t2 - t1) / (24 * 60 * 60)); // Calculate the week number int wn = delta / 7 + 1; // Handle edge cases (last week of previous year or first week of next year) int year = getYear(date); if (delta < 0) { // Given date is in the last week of the previous year year--; d1w1.tm_year = year - 1900; t1 = mktime(&d1w1); delta = int((t2 - t1) / (24 * 60 * 60)); wn = delta / 7 + 1; } else if (getDay(date) == 1 && getMonth(date) == 0 && wn == 1) { // Given date is on January 1st (Monday), so it's in the last week of the previous year year--; d1w1.tm_year = year - 1900; t1 = mktime(&d1w1); delta = int((t2 - t1) / (24 * 60 * 60)); wn = delta / 7 + 1; } return wn; } int main() { struct tm date; // Example date: January 10, 2008 date.tm_year = 2008 - 1900; // tm_year uses years since 1900 date.tm_mon = 0; // Months are 0-based date.tm_mday = 10; int weekNumber = getWeek(&date); cout << "Week number for January 10, 2008: " << weekNumber << endl; return 0; }
在此範例中,給定日期是2008 年1 月10 日,即2008 年第2 週,對應預期輸出。該程式碼可以適應處理不同的日期格式並根據需要處理邊緣情況。
以上是如何根據 ISO 8601 標準計算給定日期的周數?的詳細內容。更多資訊請關注PHP中文網其他相關文章!