Calculate the difference between two struct tm values

	tm event_date_time;
	timeval curTime;
	time_t time_now;
	time_t time_event;
	//Note time_t is num of seconds since 1970 so your tm_year must be >= 1970 or you'll get a -1 value from time_t!!

	gettimeofday(&curTime, NULL);		//Get the RPi's current time

	event_date_time.tm_year = 20;
	event_date_time.tm_mon = 1;
	event_date_time.tm_mday = 1;
	event_date_time.tm_hour = 1;
	event_date_time.tm_min = 1;
	event_date_time.tm_sec = 1;

	time_now = mktime(localtime(&curTime.tv_sec));	//Convert tm to time_t
	time_event = mktime(&event_date_time);				//Convert tm to time_t

	int difference = (int)difftime(time_now, time_event);	//Get the difference in seconds (If positive, then time_now > time_event)

Adjusting tm values (add/subtract secs, mins, days, etc)

	tm1.tm_mday += 7;
	mktime(&tm1);		//A call to this mktime() automatically adjusts the values of the members of timeptr it is called with if they are off-range (except tm_wday and tm_yday)

Adjusting the struct tm values won’t cause roll overs (e.g. if you -100 from .tm_second you will get a negative .tm_second value), you get left with the values adjusted but a potentially out of range value. mktime() is used to convert but it will correct the tm poitner it is called with so the vcalues are in range, so we don’t bother getting its result and instead use this handy side effect of calling it.

Add Or Subtract Days To A Date

This uses the answer suggested by @tenfour here.


//********** ADD OR SUBTRACT DAYS FROM A DATE **********
void add_subtract_days_from_date(struct tm *date, int days_to_add_or_subtract)
	const time_t ONE_DAY = 24 * 60 * 60 ;

	time_t date_seconds = mktime(date) + (days * ONE_DAY) ;		//Seconds since start of epoch

	*date = *localtime(&date_seconds);				//Use localtime because mktime converts to UTC so may change date
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.


Your email address will not be published.