Get yesterday’s day and date in C programming
In this tutorial, we will learn how to get or find the yesterday’s day and date in C programming.
Here I am using time.h header library.
I will first show you how to find yesterday’s exact date. Then we can easily get the day. ( Like Sunday or Monday or Tuesday etc )
#include <stdio.h> #include <time.h> int main() { // Get current time time_t now = time(NULL); // Convert it to local time structure struct tm today = *localtime(&now); // Subtract one day (24 hours) from the current time today.tm_mday -= 1; // Normalize the time structure in case of underflow mktime(&today); // Print yesterday's date in the format DD-MM-YYYY printf("Yesterday's date: %02d-%02d-%04d\n", today.tm_mday, today.tm_mon + 1, today.tm_year + 1900); return 0; }
Output:
Yesterday's date: 08-09-2024
I am running it on 9th September so I am getting this output.
You can easily change the date format as well.
To get DD-MM-YYYY this date format I am using: today.tm_mday, today.tm_mon + 1, today.tm_year + 1900
You can change the positions to change the date format.
Get yesterday’s day and date both in C
#include <stdio.h> #include <time.h> int main() { // Array of day names char* daysOfWeek[] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; // Get current time time_t now = time(NULL); // Convert it to local time structure struct tm today = *localtime(&now); // Subtract one day (24 hours) from the current time today.tm_mday -= 1; // Normalize the time structure in case of underflow mktime(&today); // Print yesterday's day and date in the format Day, DD-MM-YYYY printf("Yesterday was %s, %02d-%02d-%04d\n", daysOfWeek[today.tm_wday], today.tm_mday, today.tm_mon + 1, today.tm_year + 1900); return 0; }
Output:
Yesterday was Sunday, 08-09-2024
If you need anything else do let me know in the comment section below.
Leave a Reply