I am subtracting the current time with one minute earlier, however C++ is saying the difference is 18000 seconds, which is like 300 minutes (4 hours). Really confused as to why this is happening. This is my code:
#include <stdio.h>
#include <time.h>
#include <iostream>
int main(){
time_t timer;
struct tm t = {0};
double seconds;
t.tm_year = 122; //2022
t.tm_mon = 7 //august
t.tm_mday = 29; //29
t.tm_hour = 21; //10pm
t.tm_min = 35; //35
t.tm_sec = 0;
time(&timer); //get current time
seconds = difftime(timer, mktime(&t));
std::cout << seconds;
}
The
timefunction in the C library deals with UTC time whilemktimeassumes your local time. This is explicit in the documentation.Consider this code:
Observe that I passed
t.tm_isdst=1because I am in Chicago which is currently on daylight and I get this:So this is telling me that the time structure is just 30 seconds before the current time, which is your intended result. I also requested to print the localtime gmt offset which is minus 18,000 seconds (-5 hours), which seems correct.
Note that the timestamps
1661833680and1661833710are both in GMT as you can check on epochconverter.comNow when I run this exact code on Godbolt Compiler Explorer I get a different result:
So it is telling me now that the difference is now 5 hours. This is because it assumed that the time I was passing was in London time! But now it is 4:41am in London.
Notice that the gmtoffset is now zero indicating that this machine is in London (or set its timezone as UK).
So what I believe it is happening in your case is that you are somewhere in UTC-4 (New York?) and logged on a computer in the UK or using compiler explorer as myself.