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.
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 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.
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);
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With