Adjusting tm
struct tm Tm1 = {0};
char TextBuffer[80];
//Convert UTC string to tm
strptime("2020-08-29 11:05:13", "%Y-%m-%d %H:%M:%S", &Tm1); //Convert the character string pointed to by buf to values which are stored in the tm structure pointed to by tm, using the format specified by format
//Convert tm to string
//strftime(TextBuffer, sizeof(TextBuffer), "%Y-%m-%d %H:%M:%S", &Tm1);
//printf("UTC: %s\n", TextBuffer);
//----- ADD SOME DAYS -----
Tm1.tm_mday += 1;
Tm1.tm_mday += 1;
Tm1.tm_mday += 1;
mktime(&Tm1); //Normalise the structure (before you do this, Tm1 will output as "2020-08-32 11:05:13", after you do this "2020-09-01 11:05:13")
strftime(TextBuffer, sizeof(TextBuffer), "%Y-%m-%d %H:%M:%S", &Tm1);
printf("UTC: %s\n", TextBuffer);
//----- SUBTRACT SOME HOURS -----
Tm1.tm_hour -= 12;
mktime(&Tm1); //Normalise the structure (before you do this, Tm1 will output as "2020-09-01 -01:05:13", after you do this "2020-08-31 23:05:13")
strftime(TextBuffer, sizeof(TextBuffer), "%Y-%m-%d %H:%M:%S", &Tm1);
printf("UTC: %s\n", TextBuffer);
Adjusting time_t
//******************************************************
//********** ADD OR SUBTRACT DAYS FROM A DATE **********
//******************************************************
void AddSubtractDaysFromDate(struct tm *Date, int DaysToAddOrSubtract)
{
const time_t ONE_DAY = 24 * 60 * 60 ;
time_t DateSeconds = mktime(Date) + (DaysToAddOrSubtract * ONE_DAY) ; //Seconds since start of epoch
*Date = *localtime(&DateSeconds); //Use localtime because mktime converts to UTC so may change date
}
USEFUL?
We benefit hugely from resources on the web so we decided we should try and give back some of our knowledge and resources to the community by opening up many of our company’s internal notes and libraries through mini sites like this. We hope you find the site helpful.
Please feel free to comment if you can add help to this page or point out issues and solutions you have found, but please note that we do not provide support on this site. If you need help with a problem please use one of the many online forums.