Search code examples
ctimestrftimestrptime

How to convert character string in microseconds to struct tm in C?


I have a string that contains microseconds since the epoch. How could I convert it to a time structure?

#include <time.h>
#include <stdio.h>
#include <stdlib.h>

int main ()
{
    struct tm tm; 
    char buffer [80];
    char *str ="1435687921000000";
    if(strptime (str, "%s", &tm) == NULL)
        exit(EXIT_FAILURE); 
    if(strftime (buffer,80,"%Y-%m-%d",&tm) == 0)
        exit(EXIT_FAILURE);

    printf("%s\n", buffer);

    return 0;
}

Solution

  • Portable solution (assuming 32+ bit int). The following does not assume anything about time_t.

    Use mktime() which does not need to have fields limited to their primary range.

    #include <time.h>
    #include <stdio.h>
    #include <stdlib.h>
    
    int main(void) {
      char buffer[80];
      char *str = "1435687921000000";
    
      // Set the epoch: assume Jan 1, 0:00:00 UTC.
      struct tm tm = { 0 };
      tm.tm_year = 1970 - 1900;
      tm.tm_mday = 1;
    
      // Adjust the second's field.
      tm.tm_sec = atoll(str) / 1000000;
      tm.tm_isdst = -1;
      if (mktime(&tm) == -1)
        exit(EXIT_FAILURE);
      if (strftime(buffer, 80, "%Y-%m-%d", &tm) == 0)
        exit(EXIT_FAILURE);
      printf("%s\n", buffer);
      return 0;
    }