#include <stdio.h>
#include <time.h>
/**
* Adds a specified number of weeks to the current date.
*
* @param weeks The number of weeks to add (supports negative numbers to subtract).
* @param out_buffer Buffer to store the resulting formatted date string (e.g., "YYYY-MM-DD").
* @param buffer_size The size of the output buffer.
* @return int Returns 0 on success, or -1 on failure.
*/
int addWeeksToCurrentDate(int weeks, char *out_buffer, size_t buffer_size)
{
// 1. Get the current calendar time
time_t current_time = time(NULL);
if (current_time == (time_t)-1) {
return -1; // Failed to retrieve system time
}
// 2. Convert raw time to a broken-down local time structure
struct tm *time_info = localtime(¤t_time);
if (time_info == NULL) {
return -1; // Failed to convert time
}
// 3. Add the weeks by adjusting the day of the month (1 week = 7 days)
// Note: Modifying tm_mday directly and letting mktime normalize is idiomatic in C.
time_info->tm_mday += weeks * 7;
// 4. Normalize the struct tm using mktime()
// mktime automatically handles overflows (e.g., if day exceeds month length)
time_t updated_time = mktime(time_info);
if (updated_time == (time_t)-1) {
return -1; // Failed to normalize time
}
// 5. Format the resulting date into an ISO-8601 string (YYYY-MM-DD)
if (strftime(out_buffer, buffer_size, "%Y-%m-%d", time_info) == 0) {
return -1; // Buffer too small or formatting error
}
return 0;
}
int main()
{
int weeks_to_add = 4;
char date_buffer[11]; // Space for "YYYY-MM-DD" + null terminator
if (addWeeksToCurrentDate(weeks_to_add, date_buffer, sizeof(date_buffer)) == 0) {
printf("Date after adding %d weeks: %s\n", weeks_to_add, date_buffer);
} else {
printf("An error occurred while calculating the date.\n");
}
return 0;
}
/*
run:
Date after adding 4 weeks: 2026-12-05
*/