How to convert a string variable containing time to time_t type in c++?
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
Convert string to time_t in c
If the non-standard C function strptime() allowed:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
// Return -1 on error
time_t DR_string_to_time(const char *s) {
// Get current year
time_t t = time(NULL);
if (t == -1) {
return -1;
}
struct tm *now = localtime(&t);
if (now == NULL) {
return -1;
}
// Assume current year
struct tm DR_time = {.tm_year = now->tm_year, .tm_isdst = -1};
if (strptime(s, "%b %d %H:%M", &DR_time) == NULL) {
return -1;
}
t = mktime(&DR_time);
return t;
}
Note: "%b %d %H:%M"
(month, day, hour, minute) does not contain the year, so code needs some year to form a time_t
.
Date/time conversion: string representation to time_t
Use strptime()
to parse the time into a struct tm
, then use mktime()
to convert to a time_t
.
Convert a time (UTC ) given as a string to local time
Your problem is that if time_t
is a 32 bit value, the earliest possible date it's capable of encoding (given a 1970-1-1 epoch) is 1901-12-13.
However you're not setting the date fields of your tm
struct, which means it is defaulting to 0-0-0
which represents 1900-1-0
(since tm_day
is 1-based, you actually end up with an invalid day-of-month).
Since this isn't representable by a 32-bit time_t
the mktime
function is failing and returning -1
, a situation you're not checking for.
Simplest fix is to initialise the date fields of the tm
struct to something a time_t
can represent:
time_sample_struct.tm_year = 114;
time_sample_struct.tm_mday = 1;
Related Topics
C++ Catch Blocks - Catch Exception by Value or Reference
Why Does Call-By-Value Example Not Modify Input Parameter
C++ Get Name of Type in Template
Dividing Two Integers to Produce a Float Result
How to Concatenate Multiple C++ Strings on One Line
How to Start a New Cuda Project in Visual Studio 2008
Why Is My Integer Math With Std::Pow Giving the Wrong Answer
Mixing Cout and Printf For Faster Output
Ull Suffix on a Numeric Literal
What Belongs in an Educational Tool to Demonstrate the Unwarranted Assumptions People Make in C/C++
Splitting a C++ Std::String Using Tokens, E.G. ";"
What Is the Worst Real-World Macros/Pre-Processor Abuse You'Ve Ever Come Across
How to Get a Process Handle by Its Name in C++
What Makes More Sense - Char* String or Char *String
Copy Constructor and = Operator Overload in C++: Is a Common Function Possible
How to Programmatically Get the Version of a Dll or Exe File
Overload Resolution Failure When Streaming Object Via Implicit Conversion to String