Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a string variable containing time to time_t type in c++?

Tags:

c++

time

I have a string variable containing time in hh:mm:ss format. How to convert it into time_t type? eg: string time_details = "16:35:12"

Also, how to compare two variables containing time so as to decide which is the earliest? eg : string curr_time = "18:35:21" string user_time = "22:45:31"

like image 319
R11G Avatar asked Jun 26 '12 18:06

R11G


People also ask

How to convert string into time in c?

The strptime() function is used to convert a string representation of time to the tm structure (broken-down time). The strptime() function is the converse function to the strftime() function. char *strptime(const char *s, const char *format, struct tm *tm);

How do you add time to a string?

var dateValue = new Date("2021-01-12 10:10:20"); Use new Date() along with setHours() and getHours() to add time.

What is Strptime in C?

Description. The strptime() function converts the character string pointed to by buf to values that are stored in the tm structure pointed to by tm, using the format specified by format. The format contains zero or more directives.


3 Answers

With C++11 you can now do

struct 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 = mktime(&tm);

see std::get_time and strftime for reference

like image 130
v2blz Avatar answered Oct 11 '22 22:10

v2blz


You can use strptime(3) to parse the time, and then mktime(3) to convert it to a time_t:

const char *time_details = "16:35:12";
struct tm tm;
strptime(time_details, "%H:%M:%S", &tm);
time_t t = mktime(&tm);  // t is now your desired time_t
like image 29
Adam Rosenfield Avatar answered Oct 11 '22 21:10

Adam Rosenfield


This should work:

int hh, mm, ss;
struct tm when = {0};

sscanf_s(date, "%d:%d:%d", &hh, &mm, &ss);


when.tm_hour = hh;
when.tm_min = mm;
when.tm_sec = ss;

time_t converted;
converted = mktime(&when);

Modify as needed.

like image 44
Mahmoud Al-Qudsi Avatar answered Oct 11 '22 21:10

Mahmoud Al-Qudsi