C Exercises: Print the date and time before 24 months
8. Date and Time 24 Months Ago
Write a program in C to print the date and time before 24 months.
Sample Solution:
C Code:
// Define _POSIX_C_SOURCE to enable specific POSIX features
#define _POSIX_C_SOURCE 200112L
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
int main(void)
{
// Set the timezone environment variable to "Asia/Calcutta"
setenv("TZ", "/usr/share/zoneinfo/Asia/Calcutta", 1);
// Get the current local time and store it in a tm structure
struct tm tm = *localtime(&(time_t){time(NULL)});
// Print today's date and check if Daylight Saving Time (DST) is in effect
printf("\nToday is : %s", asctime(&tm));
printf("(DST is %s)\n", tm.tm_isdst ? "in effect" : "not in effect");
// Subtract 24 months from the month value of the stored time structure
tm.tm_mon -= 24;
// Normalize the modified time structure using mktime
mktime(&tm);
// Print the date from 24 months ago and check if DST was in effect
printf("\n24 months ago the date was : %s", asctime(&tm));
printf("(DST was %s)\n\n", tm.tm_isdst ? "in effect" : "not in effect");
}
Output:
Today is : Thu Aug 3 17:27:16 2017 (DST is not in effect) 24 months ago the date was : Mon Aug 3 17:27:16 2015 (DST was not in effect)
N.B.: The result may varry for your current system date and time.
Flowchart:
For more Practice: Solve these Related Problems:
- Write a C program to compute and print the date and time exactly 24 months before the current date, accounting for leap years.
- Write a C program to display the current date and time, then subtract 24 months and print the adjusted date in a custom format.
- Write a C program to calculate the date and time 24 months ago using calendar arithmetic and display both the original and resulting dates.
- Write a C program to subtract 24 months from the current time, handle day-of-month overflow, and then output the final date and time.
C Programming Code Editor:
Previous: Write a program in C to convert a time_t object to calendar time expressed as local time.
Next: Write a program in C to show the first of calendar time.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.