Home > Backend Development > C++ > How to Determine the Earlier Time Between Two String Time Values in C ?

How to Determine the Earlier Time Between Two String Time Values in C ?

DDD
Release: 2024-11-29 22:34:10
Original
306 people have browsed it

How to Determine the Earlier Time Between Two String Time Values in C  ?

Conversion of String Time to time_t

Converting a string containing time in "hh:mm:ss" format to time_t in C can be achieved in various ways.

One method is to leverage C 11's advanced time and date manipulation capabilities with and libraries. You can utilize the following steps:

  • Define a tm struct.
  • Utilize an istringstream to read the time string.
  • Extract the time components using get_time.
  • Construct a time_t value using mktime.

For example:

std::tm tm;
std::istringstream ss("16:35:12");
ss >> std::get_time(&tm, "%H:%M:%S"); // or just %T in this case
std::time_t time = std::mktime(&tm);
Copy after login

Comparing Time Variables for Earliest Value

To compare two strings containing time, you can either compare their corresponding time_t representations or use string comparison techniques.

Using time_t values, you can directly compare them using std::less. For example:

std::string curr_time = "18:35:21";
std::string user_time = "22:45:31";
std::istringstream ss_curr(curr_time);
std::istringstream ss_user(user_time);
std::tm tm_curr, tm_user;
ss_curr >> std::get_time(&tm_curr, "%H:%M:%S");
ss_user >> std::get_time(&tm_user, "%H:%M:%S");
std::time_t time_curr = std::mktime(&tm_curr);
std::time_t time_user = std::mktime(&tm_user);

if (time_curr < time_user) {
  std::cout << curr_time << " is earlier than " << user_time << std::endl;
} else {
  std::cout << user_time << " is earlier than " << curr_time << std::endl;
}
Copy after login

Alternatively, string comparison can be used, assuming both times are in the same format:

if (curr_time < user_time) {
  std::cout << curr_time << " is earlier than " << user_time << std::endl;
} else {
  std::cout << user_time << " is earlier than " << curr_time << std::endl;
}
Copy after login

The above is the detailed content of How to Determine the Earlier Time Between Two String Time Values in C ?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template