Home > Backend Development > C++ > How to Convert a String Time to time_t in C ?

How to Convert a String Time to time_t in C ?

Barbara Streisand
Release: 2024-11-21 10:10:13
Original
911 people have browsed it

How to Convert a String Time to time_t in C  ?

Converting String Time to time_t in C

When working with time data in C , it's often necessary to convert strings containing time in the "hh:mm:ss" format to the time_t type. Here's how you can achieve this:

#include <iostream>
#include <iomanip>
#include <sstream>
#include <ctime>

int main() {
  std::string time_details = "16:35:12";
  
  struct std::tm tm;
  std::istringstream ss(time_details);
  ss >> std::get_time(&tm, "%H:%M:%S"); // or use "%T" for this case
  std::time_t time_value = std::mktime(&tm);

  std::cout << "Converted time: " << std::put_time(std::gmtime(&time_value), "%H:%M:%S") << '\n';

  return 0;
}
Copy after login

This code demonstrates:

  • Converting to time_t: We convert the string time to a time_t variable named time_value using stream parsing of the string and the std::mktime function.
  • Comparing Time Variables: To compare two time_t variables (e.g., curr_time and user_time), you can use the following method:

    if (curr_time < user_time) {
    std::cout << "curr_time is earlier than user_time.\n";
    } else if (curr_time == user_time) {
    std::cout << "curr_time and user_time are the same.\n";
    } else {
    std::cout << "user_time is earlier than curr_time.\n";
    }
    Copy after login

The above is the detailed content of How to Convert a String Time to time_t 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template