Home >Backend Development >C++ >How do you calculate the week number of a given date based on the ISO 8601 standard?
Calculating Week Number Given a Date
In many applications, it's essential to determine the week number for a given date. This information is useful in industries like planning and scheduling. This article explores an algorithm and a code example to calculate the week number based on ISO 8601.
ISO 8601 Definition
The ISO 8601 standard defines a week number based on the following rules:
Algorithm
To calculate the week number, follow these steps:
C Code Example
#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; }
In this example, the given date is January 10, 2008, which falls in Week 2 of 2008, corresponding to the expected output. The code can be adapted to process different date formats and handle edge cases as needed.
The above is the detailed content of How do you calculate the week number of a given date based on the ISO 8601 standard?. For more information, please follow other related articles on the PHP Chinese website!