Date/time conversion: string representation to time_t

How do I convert a date string, formatted as "MM-DD-YY HH:MM:SS", to a time_t value in either C or C++?

Answers


Use strptime() to parse the time into a struct tm, then use mktime() to convert to a time_t.


In the absence of strptime you could use sscanf to parse the data into a struct tm and then call mktime. Not the most elegant solution but it would work.


Boost's date time library should help; in particular you might want to look at http://www.boost.org/doc/libs/1_37_0/doc/html/date_time/date_time_io.html


I'm afraid there isn't any in Standard C / C++ . There is the POSIX function strptime which can convert to struct tm, which can then be converted to time_t using mktime.

If you are aiming for cross platform compatibility, better use boost::date_time, which has sophisticated functions for this.


Note that strptime mentioned in accepted answer is not portable. Here's handy C++11 code I use to convert string to std::time_t :

static std::time_t to_time_t(const std::string& str, bool is_dst = false, const std::string& format = "%Y-%b-%d %H:%M:%S")
{
    std::tm t = {0};
    t.tm_isdst = is_dst ? 1 : 0;
    std::istringstream ss(str);
    ss >> std::get_time(&t, format.c_str());
    return mktime(&t);
}

You can call it like this:

std::time_t t = to_time_t("2018-February-12 23:12:34");

You can find string format parameters here.


best way to convert a date string, formatted as "MM-DD-YY HH:MM:SS", to a time_t

Restricting code to standard C library functions is looking for the inverse of strftime(). To expand @Rob general idea, uses sscanf().

Use "%n" to detect completed scan

time_t date_string_to_time(const char *date) {
  struct tm tm = { 0 }; // Important, initialize all members
  int n = 0;
  sscanf(date, "%d-%d-%d %d:%d:%d %n", &tm.tm_mon, &tm.tm_mday, &tm.tm_year,
      &tm.tm_hour, &tm.tm_min, &tm.tm_sec, &n);
  // If scan did not completely succeed or extra junk
  if (n == 0 || date[n]) {
    return (time_t) -1;
  }
  tm.tm_isdst = -1; // Assume local daylight setting per date/time
  tm.tm_mon--;      // Months since January
  // Assume 2 digit year if in the range 2000-2099, else assume year as given
  if (tm.tm_year >= 0 && tm.tm_year < 100) {
    tm.tm_year += 2000;
  }
  tm.tm_year -= 1900; // Years since 1900
  time_t t = mktime(&tm);
  return t;
}

Additional code could be used to insure only 2 digit timestamp parts, positive values, spacing, etc.

Note: this assume the "MM-DD-YY HH:MM:SS" is a local time.


    static time_t MKTimestamp(int year, int month, int day, int hour, int min, int sec)
{
    time_t rawtime;
    struct tm * timeinfo;

    time ( &rawtime );
    timeinfo = gmtime ( &rawtime );
    timeinfo->tm_year = year-1900 ;
    timeinfo->tm_mon = month-1;
    timeinfo->tm_mday = day;
    timeinfo->tm_hour = hour;
    timeinfo->tm_min = min;
    timeinfo->tm_sec = sec;
    timeinfo->tm_isdst = 0; // disable daylight saving time

    time_t ret = mktime ( timeinfo );

    return ret;
}

 static time_t GetDateTime(const std::string pstr)
{
    try 
    {
        // yyyy-mm-dd
        int m, d, y, h, min;
        std::istringstream istr (pstr);

        istr >> y;
        istr.ignore();
        istr >> m;
        istr.ignore();
        istr >> d;
        istr.ignore();
        istr >> h;
        istr.ignore();
        istr >> min;
        time_t t;

        t=MKTimestamp(y,m,d,h-1,min,0);
        return t;
    }
    catch(...)
    {

    }
}

Need Your Help

Dynamic Select list using sql data

php list select dynamic option

I am trying to create a select drop-down list using php. Every time i try, i get an error.

Doing a matrix multiplication in reverse

java opengl math matrix lwjgl

Follow-up for: Calculating world coordinates from camera coordinates