2

I want to right a function that would compare two ISO 6801 time stamps and return the most recent one. I'm having trouble figuring out an easy way to create a function

For example Given string s1 = 2012-10-10 09:42:00; and string s2 = 2012-10-10 09:52:00;

compare_timestamp(s1,s2) would return s2

pyCthon
  • 11,746
  • 20
  • 73
  • 135
  • 4
    ISO 8601 is designed so that you can just compare the strings lexicographically (e.g. via `strcmp`) to determine their order in time. – Nemo Dec 19 '12 at 02:03
  • @Nemo so convert both of `std::string`'s to `const char*` then use `strcmp`? – pyCthon Dec 19 '12 at 02:13

2 Answers2

4

If you juste need to find the more recent, a string comparison is sufficent.

string &compare_timestamp(string &s1, string &s2) {
    return s1.compare(s2) > 0 ? s1 : s2;
}
BAK
  • 972
  • 8
  • 23
2
std::string & compare_timestamp(std::string & lhs, std::string & rhs) {
    return std::max(lhs, rhs);
}
std::string const & compare_timestamp(std::string const & lhs, std::string const & rhs) {
    return std::max(lhs, rhs);
}

Now, a better solution would be to create a TimeStamp class rather than working with a std::string directly. The TimeStamp could internally hold a std::string and overload operator< to just defer to std::string::operator<, but you would be using strong types

Community
  • 1
  • 1
David Stone
  • 26,872
  • 14
  • 68
  • 84