Home > Net >  Convert string to time_t in c
Convert string to time_t in c

Time:11-16

Hi I need to convert the variable time, containing a string to a time_t type with the format i would like to print after:

   time_t t = time(NULL);
   struct tm *tm = localtime(&t);
   char time[100];
   strftime(time, 100, "%b %d %H:%M", tm);
   

I wouldn't like to make any modifications in the code above and keep the format I chose. Thank you!

CodePudding user response:

If the non-standard C function strptime() allowed:

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

// Return -1 on error
time_t DR_string_to_time(const char *s) {
  // Get current year
  time_t t = time(NULL);
  if (t == -1) {
    return -1;
  }
  struct tm *now = localtime(&t);
  if (now == NULL) {
    return -1;
  }

  // Assume current year
  struct tm DR_time = {.tm_year = now->tm_year, .tm_isdst = -1}; 
  if (strptime(s, "%b %d %H:%M", &DR_time) == NULL) {
    return -1;
  }
  t = mktime(&DR_time);
  return t;
}

Note: "%b %d %H:%M" (month, day, hour, minute) does not contain the year, so code needs some year to form a time_t.

  • Related