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.
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);