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
}
Feel free to comment if you can add help to this page or point out issues and solutions you have found. I do not provide support on this site, if you need help with a problem head over to stack overflow.

Comments

Your email address will not be published. Required fields are marked *