How to Convert a String Variable Containing Time to Time_T Type in C++

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



Leave a reply



Submit