0

I have a time string like this "132233" (Time only no date) and i want to convert it into local time. So, in order to use the function localtime(), I first converted my string into time_t using mktime() (thanks to How to convert a string variable containing time to time_t type in c++? )and then printed the time after conversion using strftime as shown in (http://www.cplusplus.com/reference/ctime/strftime/) I am getting a serious run time error. Can any one please tell me whats wrong. Thanks in advance

int main()
{
    string time_sample="132233";

    std::string s_hrs (time_sample.begin(), time_sample.begin()+2);                                                 
    std::string s_mins (time_sample.begin()+2,time_sample.begin()+4);
    std::string s_secs (time_sample.begin()+4,time_sample.begin()+6);

    int hrs = atoi(s_hrs.c_str());
    int mins = atoi(s_mins.c_str());
    int secs = atoi(s_secs.c_str());

    struct tm time_sample_struct = {0};
    time_sample_struct.tm_hour = hrs;
    time_sample_struct.tm_min = mins;
    time_sample_struct.tm_sec = secs;

    time_t converted_time;
    converted_time = mktime(&time_sample_struct);

    struct tm * timeinfo;
    char buffer[80];
    timeinfo = localtime(&converted_time);
    strftime(buffer,80,"%I:%M:%S",timeinfo);
    puts(buffer);                                                               
    cout<<endl;
    getch();
    return 0;
}
Community
  • 1
  • 1
Dan K
  • 218
  • 5
  • 12

1 Answers1

0

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;
Jonathan Potter
  • 36,172
  • 4
  • 64
  • 79