Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

converting string into time using sscanf

Tags:

c

string

time

I am trying to convert time string into time format in C on windows. As i just have hour, minutes and seconds in my string, so tried to parse the string using sscanf into time format and then use mktime. But somehow its not converting it into time format. To check, i tried to print the converted time into string back. The code looks like:

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);
like image 922
learningpal Avatar asked Feb 09 '23 14:02

learningpal


1 Answers

Before calling mktime(), code needs to initialize 7+ fields of tm_struct(): year, month,day, hour min, sec, isdst and potentially others.

2 exceptions: .tm_yday, .tm_wday do not need assignment before calling mktime().

The year, month, day should be set to something reasonable: let us use 2000 Jan 1. Alternatively code could use time_t() to get today.

Code uses ms hinting that the value is in milliseconds. It is not. It is still in seconds.

Use local time_t variable rather than allocating one. malloc() not needed.

struct tm tm = {0};
tm.tm_year = 2000 - 1900;  // Years from 1900
tm.tm_mon = 1 - 1; // Months from 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
like image 68
chux - Reinstate Monica Avatar answered Feb 12 '23 04:02

chux - Reinstate Monica