Comparing Times

Hello All, I currently have a small problem. In my game, I have need of being able to record the current time, to save as a string (will save string to json using my own means), and then reload said string and compare to current time. My goal is to end with a value with the number of days since the last time was written to the file. Aka, it can be (10.6 days) or something. I just need a way of recording time to string, and comparing the times. I have tried using diff-time, but to no avail. Here is something I have tried.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <ctime>
#include <iostream>
using namespace std;

int main() {
	time_t t = time(0);   // get time now
	struct tm * now = localtime(&t);
	cout << (now->tm_year + 1900) << '-'
		<< (now->tm_mon + 1) << '-'
		<< now->tm_mday
		<< endl;
	
	time_t old = time(0);

	struct time * now = localtime(&old);

	cout << (now->time_year + 1900);
}
Last edited on
Something along these lines, perhaps:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <iostream>
#include <string>
#include <ctime>

static constexpr const char* time_fmt = "%Y%m%d%H%M%S" ;  // eg. 20180302022715

std::string timestamp( std::time_t t = std::time(nullptr) )
{
    char buffer[64] {} ;
    std::strftime( buffer, sizeof(buffer), time_fmt, std::localtime( std::addressof(t) ) ) ;
    return buffer ;
}

std::time_t to_time_t( const std::string& timestamp ) // throws on bad timestamp
{
    std::tm tm {} ;
    tm.tm_year = std::stoi( timestamp.substr(0,4) ) - 1900 ;
    tm.tm_mon = std::stoi( timestamp.substr(4,2) ) - 1 ;
    tm.tm_mday = std::stoi( timestamp.substr(6,2) ) ;
    tm.tm_hour = std::stoi( timestamp.substr(8,2) ) ;
    tm.tm_min = std::stoi( timestamp.substr(10,2) ) ;
    tm.tm_sec = std::stoi( timestamp.substr(12,2) ) ;

    return std::mktime( std::addressof(tm) ) ;
}

double days_from( const std::string& timestamp_begin, const std::string& timestamp_end )
{
    static constexpr int SECS_PER_DAY = 24 * 60 * 60 ;
    return std::difftime( to_time_t(timestamp_end), to_time_t(timestamp_begin) ) / SECS_PER_DAY ;
}

int main()
{
    const auto str = timestamp() ;
    std::cout << str << '\n' // eg. 20180302022715
              << std::boolalpha << ( str == timestamp( to_time_t(str) ) ) << '\n' // true
              << days_from( str, timestamp( to_time_t(str) + 36*60*60 ) ) << '\n' // 1.5 if it's unix time
              << days_from( str, timestamp( to_time_t(str) - 60*60*60 ) ) << '\n' ; // -2.5 if it's unix time
}

http://coliru.stacked-crooked.com/a/bdde4e3a062c4013
Topic archived. No new replies allowed.