Reputation: 2453
I have a text file with records in it. I need to decide if the time (which is part of the record structure) is between 2 times (stored in strings) that represents the lower and upper range. In the file the time is represented in 145540123456, which means 14 is the hour, 55 - minutes, 40 - seconds, 123456 - micrseconds accurate.
The upper and lower time that I get to decide if it is in the range, I get it as a string in the same format for instance "093000000000". How do I make the calculation, do I need to do it with time_t and time library?
Note: I can't use Boost.
Upvotes: 0
Views: 450
Reputation: 42969
The format you specify has the simple advantage that sorting these time-strings alpha-numerically will keep them in the correct order.
Therefore, using strcmp
(simple C function if using null-terminated char * buffers), or the comparison operators for std::string
can allow you to determine easily if a certain time string belongs to an interval.
These methods can lead to very few calculations, if, for example, the first character of the strings you compare differs, since the standard functions should be smart enough to stop comparing the strings as soon as they have determined the result.
Upvotes: 6
Reputation: 59841
The best way (c) to handle date/time calculations in C++ is the Boost.Date_Time library.
Unfortunately your strings aren't in any standard format. So you would have to parse them yourself and use this as input to a posix time duration.
If you cannot use any library you can simply define a struct with hour, minutes, seconds and microseconds members and operator<
.
Then simply parse the input into those structs and compare them.
Another options is to convert each duration in microseconds. The comparison becomes trivial then.
Upvotes: 0
Reputation: 89232
In this case, just convert it to a number and compare. Your format puts the most significant digits on the left. Your highest possible number is 235,959,999,999
, which won't fit in a unsigned long.
A simple way is to split it at the HHMMSS and mmmmmm -- if the first numbers are equal, compare the second.
Upvotes: 1
Reputation: 2454
If you are not substracting those numbers, you should be able to just compare them as numbers. The one that represents longer time will always be a greater number too. This is because you have the units that weigh most at the left end (hours) and the units that weigh least at the right end (microseconds), which is the same system as the normal numbers use.
Just convert it to unsigned int64 or something, not just int, as that will get overflowed with a number like 145540123456.
Upvotes: 1