You can manipulate the contents of the ts
struct before passing it to strftime
. The day of the month is contained in the tm_mday
member. Basic procedure:
/**
* If today is the 1st, subtract 1 from the month
* and set the day to the last day of the previous month
*/
if (ts->tm_mday == 1)
{
/**
* If today is Jan 1st, subtract 1 from the year and set
* the month to Dec.
*/
if (ts->tm_mon == 0)
{
ts->tm_year--;
ts->tm_mon = 11;
}
else
{
ts->tm_mon--;
}
/**
* Figure out the last day of the previous month.
*/
if (ts->tm_mon == 1)
{
/**
* If the previous month is Feb, then we need to check
* for leap year.
*/
if (ts->tm_year % 4 == 0 && ts->tm_year % 400 == 0)
ts->tm_mday = 29;
else
ts->tm_mday = 28;
}
else
{
/**
* It's either the 30th or the 31st
*/
switch(ts->tm_mon)
{
case 0: case 2: case 4: case 6: case 7: case 9: case 11:
ts->tm_mday = 31;
break;
default:
ts->tm_mday = 30;
}
}
}
else
{
ts->tm_mday--;
}
Edit: Yes, days of the month are numbered from 1 whereas everything else (seconds, minutes, hours, weekdays, and days of the year) are numbered from 0.