Home  >  Article  >  Backend Development  >  How to Convert a String Representing Time to a `time_t` in C ?

How to Convert a String Representing Time to a `time_t` in C ?

Linda Hamilton
Linda HamiltonOriginal
2024-11-10 07:41:02149browse

How to Convert a String Representing Time to a `time_t` in C  ?

Converting a String Representing Time to time_t in C

When working with time in C , you may encounter scenarios where you have a string that represents a specific time and need to convert it into the portable time_t data type. The time_t type represents time as the number of seconds elapsed since January 1, 1970, 00:00:00 UTC.

Conversion to time_t

In C 11 and later, the std::get_time function can be used to parse a string into a std::tm struct, which can then be converted to time_t using mktime:

#include <iostream>
#include <sstream>
#include <time.h>

int main() {
  std::string time_details = "16:35:12";
  std::tm tm;
  std::istringstream ss(time_details);
  ss >> std::get_time(&tm, "%H:%M:%S");
  std::time_t time = mktime(&tm);

  // Print the converted time_t
  std::cout << "Converted time: " << time << std::endl;

  return 0;
}

Comparing Two Times

Once you have multiple times in the time_t format, you can compare them to determine which is earlier.

#include <iostream>
#include <time.h>

int main() {
  std::string curr_time = "18:35:21"; // Current time
  std::string user_time = "22:45:31"; // User's time
  std::tm curr_tm, user_tm;
  std::istringstream ss;

  // Parse both times
  ss.str(curr_time);
  ss >> std::get_time(&curr_tm, "%H:%M:%S");
  ss.clear();
  ss.str(user_time);
  ss >> std::get_time(&user_tm, "%H:%M:%S");

  // Compare the time_t values
  std::time_t curr_secs = mktime(&curr_tm);
  std::time_t user_secs = mktime(&user_tm);

  if (curr_secs < user_secs) {
    std::cout << "Current time is earlier than user's time" << std::endl;
  } else {
    std::cout << "User's time is earlier than current time" << std::endl;
  }

  return 0;
}

The above is the detailed content of How to Convert a String Representing Time to a `time_t` in C ?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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