Convert string in time using sscanf

I am trying to convert a timeline to a time format in windows C. Since there is only an hour, minutes and seconds in my line, so I tried to parse the line using sscanf into a time format and then use mktime. But for some reason this does not turn it into a time format. To check, I tried to print the converted time to a string back. The code looks like this:

struct tm tm; char time_buffer[100]; int hh, mm; float ms; time_t time_value; char *timestamp = {"16:11:56.484"}; sscanf(timestamp, "%d:%d:%f", &hh, &mm,&ms); tm.tm_hour =hh; tm.tm_min = mm; tm.tm_sec = ms*1000; tm.tm_isdst = -1; time_value = malloc(100*sizeof(char)); time_value = mktime(&tm); if (time_value==-1) printf ("unable to make time"); strftime(time_buffer, sizeof(time_buffer), "%c", &tm); printf(time_buffer); 
+3
source share
2 answers

Before calling mktime() code must initialize 7 tm_struct() fields: year, month,day, hour min, sec, isdst . Others may also be initialized, but they are ignored.

Year, month, day should be set to something reasonable: let's use January 2000 1. Alternatively, the code can use time_t() to get today.

The code uses ms , indicating that the value is milliseconds. Is not. It is still in seconds.

Use the local variable time_t instead of highlighting it. malloc() not required.

 struct tm tm; tm.tm_year = 2000 - 1900; // Years from 1900 tm.tm_mon = 1 - 1; // Months form January tm.tm_mday = 1; char time_buffer[100]; int hh, mm; float ss; time_t time_value; char *timestamp = "16:11:56.484"; if (sscanf(timestamp, "%d:%d:%f", &hh, &mm,&ss) != 3) Handle_BadData(); tm.tm_hour = hh; tm.tm_min = mm; tm.tm_sec = roundf(ss); // or simply = ss; tm.tm_isdst = 0; // Keep in standard time // time_value = malloc(100*sizeof(char)); time_value = mktime(&tm); if (time_value == -1) { printf ("unable to make time"); } else { strftime(time_buffer, sizeof(time_buffer), "%c", &tm); printf(time_buffer); } // Sat Jan 1 16:11:56 2000 
+2
source
  • you do not initialize your struct tm , but just set tm_hour , tm_min , tm_sec and tm_isdst . All other fields are not initialized and therefore have unknown values.
  • If you initialized your struct tm with memset(&tm, 0, sizeof(tm)) , you probably still get an error, because the fields stored in the structure do not all allow 0 as a valid value ( tm_mday ). For reference see docs .
  • The value you put in tm_sec will most likely be invalid. You really want it to be ms/1000 , not ms*1000 .
+4
source

All Articles