Home >Backend Development >C++ >How to Calculate the Week Number of a Given Date in C ?

How to Calculate the Week Number of a Given Date in C ?

DDD
DDDOriginal
2024-11-26 10:50:10433browse

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:

  1. Identify the first day of the first week of the year: Determine the Monday that is closest to January 1st of the given year. This can be found mathematically by adding or subtracting days from January 1st based on its weekday (Sunday: 1, Monday: 0, Tuesday: -1, Wednesday: -2, Thursday: -3, Friday: 3, Saturday: 2).
  2. Calculate the number of full weeks between the given date and the first day of week 1: Subtract the first day of week 1 from the given date to get the number of elapsed days. Dividing this by 7 will yield the number of complete weeks.
  3. Calculate the remainder: Determine the remaining days by dividing elapsed days by 7 and calculating the remainder. This represents the number of days into the current week.
  4. Assign week number: Combining the whole weeks and remaining days yields the week number.

For instance, for January 10th, 2008:

  1. The first day of week 1 is January 7th, 2008, which is a Monday.
  2. The number of elapsed days is 10 - 7 = 3.
  3. The number of whole weeks is 3 / 7 = 0.
  4. The remainder is 3 days.
  5. Therefore, the week number is 2 (since we start from week 1).

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn