How to calculate the date six months from the current date in C

2 Answers

0 votes
#include <stdio.h>
#include <time.h>

int main() {
    // Get the current time
    time_t current_time = time(NULL);
    if (current_time == -1) {
        perror("Failed to get the current time");
        return 1;
    }

    // Convert to a struct tm
    struct tm *current_date = localtime(&current_time);
    if (current_date == NULL) {
        perror("Failed to convert time to local time");
        return 1;
    }

    // Add six months (approximation: 6 months = 183 days)
    current_date->tm_mon += 6;

    // Normalize the date (handles overflow of months, days, etc.)
    mktime(current_date);

    // Print the new date
    printf("Date six months from now: %02d-%02d-%04d\n",
           current_date->tm_mday,
           current_date->tm_mon + 1, // tm_mon is 0-based
           current_date->tm_year + 1900); // tm_year is years since 1900

    return 0;
}

 
 
/*
run:
  
Date six months from now: 11-12-2025
 
*/

 



answered Jun 11, 2025 by avibootz
0 votes
#include <stdio.h>
#include <time.h>

struct tm calculate_future_date(int months_to_add) {
    // Get the current time
    time_t current_time = time(NULL);
    if (current_time == -1) {
        perror("Failed to get the current time");
    }

    // Convert to a struct tm
    struct tm *current_date = localtime(&current_time);
    if (current_date == NULL) {
        perror("Failed to convert time to local time");
    }

    // Add specified number of months
    current_date->tm_mon += months_to_add;

    // Normalize the date (handles overflow of months, days, etc.)
    mktime(current_date);

    return *current_date;  // Return the modified struct tm
}

int main() {
    struct tm future_date = calculate_future_date(6);

    // Print the new date
    printf("Date six months from now: %02d-%02d-%04d\n",
           future_date.tm_mday,
           future_date.tm_mon + 1, // tm_mon is 0-based
           future_date.tm_year + 1900); // tm_year is years since 1900

    return 0;
}

 

/*
run:
  
Date six months from now: 11-12-2025
 
*/

 



answered Jun 11, 2025 by avibootz

Related questions

...