Home >Backend Development >C++ >How to Calculate the Week Number of a Given Date in C ?
How to Calculate the Week Number for a Given Date
Given a date, determining the week number for that date within its respective year can be achieved through the following steps:
For instance, for January 10th, 2008:
In C , this algorithm can be implemented as follows:
#include <iostream> #include <ctime> using namespace std; int main() { // Get the user's input date tm inputDate; cout << "Enter the date (YYYY-MM-DD): "; cin >> get_time(&inputDate, "%Y-%m-%d"); // Calculate the first day of week 1 tm firstDayOfWeek1; time_t firstDaySeconds = mktime(&inputDate); // Calculate the number of elapsed days long elapsedDays = difftime(firstDaySeconds, mktime(&firstDayOfWeek1)); // Calculate the number of whole weeks int wholeWeeks = elapsedDays / (7 * 24 * 60 * 60); // Calculate the remainder int remainder = elapsedDays % (7 * 24 * 60 * 60); // Calculate the week number int weekNumber = wholeWeeks + (remainder > 0); // Print the week number cout << "The week number is: " << weekNumber << endl; return 0; }
The above is the detailed content of How to Calculate the Week Number of a Given Date in C ?. For more information, please follow other related articles on the PHP Chinese website!