0

How can I convert a command line argument in the format of HH:MM:SS thats a string into a time_t type? The only solutions I've found have been for C++ and to convert time_t into string but not the other way around in C.

Thanks.

edit: I need to implement it without string.h

I'm trying to convert a command line argument and a string (e.g."13:32:41" and "13:40:35") into a time_t format so I can use difftime(tm1,tm2) to get the difference.

Would the below work?

time_t string_to_time(const char* time) {
  struct tm tm = {0};
  sscanf(time, "%H:%M:%S", &tm.tm_hour,&tm.tm_min, &tm.tm_sec);
  time_t t=mktime(&tm);
  return t;
 }
Dennis Liu
  • 43
  • 5
  • You have to parse the string e.g. using `sscanf`. – Paul Ogilvie Mar 23 '21 at 11:51
  • strtok() function may help – Emre İriş Mar 23 '21 at 11:52
  • 1
    Maybe `strptime` and `mktime`, see https://pubs.opengroup.org/onlinepubs/007904875/functions/strptime.html. Note that a `time_t` is usually the time since 01 Jan 1970, but you have a time only without date. You should [edit] your question and explain what result you want to get, maybe using examples of input and expected output. – Bodo Mar 23 '21 at 12:00
  • Edited the question to make it more clear – Dennis Liu Mar 23 '21 at 12:13

1 Answers1

0

Would the below work?

Yes (for valid input). It will return number of seconds at 1970/1/1 HH:MM:SS since 1970/1/1 00:00:00.

But I do not get the point. Is it really soooo hard to write:

int hour, min, sec;
if (sscanf(time, "%d:%d:%d", &hour, &min, &sec) != 3) return -1;
return hour * 3600 + min * 60 + sec;

to convert time_t into string but not the other way around in C.

My first google hit How to convert a string variable containing time to time_t type in c++? uses strptime is indeed for C++. Sadly strptime is not part of C time.h, it comes from POSIX strptime available on linux and such. For windows, see ex. strptime() equivalent on Windows? .

KamilCuk
  • 120,984
  • 8
  • 59
  • 111