Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Do I Get Yesterday's Date In C?

I am wanting to get yesterday's date into a char in the format: YYYYMMDD (with no slashes dots etc.).

I am using this code to get today's date:

time_t now;

struct tm  *ts;  
char yearchar[80]; 

now = time(NULL);  
ts = localtime(&now);

strftime(yearchar, sizeof(yearchar), "%Y%m%d", ts);

How would I adapt this code so that it is generating yesterday's date instead of today's?

Many Thanks.

like image 606
baxterma Avatar asked Jan 20 '11 15:01

baxterma


People also ask

How to get previous date in C?

To get previous day's date we are using a user define function getYesterdayDate() which has date structure as pointer, any changes made in the structure date inside this function will reflect to the actual values in the main().

How do I find yesterday's date?

How do you get yesterdays' date using JavaScript? We use the setDate() method on yesterday , passing as parameter the current day minus one. Even if it's day 1 of the month, JavaScript is logical enough and it will point to the last day of the previous month.


3 Answers

The mktime() function will normalise the struct tm that you pass it (ie. it will convert out-of-range dates like 2020/2/0 into the in-range equivalent 2020/1/31) - so all you need to do is this:

time_t now;
struct tm  *ts;  
char yearchar[80]; 

now = time(NULL);
ts = localtime(&now);
ts->tm_mday--;
mktime(ts); /* Normalise ts */
strftime(yearchar, sizeof(yearchar), "%Y%m%d", ts);
like image 112
caf Avatar answered Oct 08 '22 03:10

caf


how about adding

now = now - (60 * 60 * 24)

Might fail in some VERY rare corner cases (e.g. during leapseconds) but should do what you want 99.999999% of the time.

like image 21
Tyler Eaves Avatar answered Oct 08 '22 04:10

Tyler Eaves


Simply subtracting one day's worth of seconds from time(NULL); should do. Change this line:

now = time(NULL);

to this:

now = time(NULL) - (24 * 60 * 60);
like image 2
orlp Avatar answered Oct 08 '22 05:10

orlp