C Exercises: Print the date and time before 24 months
C Date Time: Exercise-8 with Solution
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");
}
Sample 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:
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.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/c-programming-exercises/datetime/c-datetime-exercise-8.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics