10

Is there a C/C++/STL/Boost clean method to convert a date time string to epoch time (in seconds)?

yyyy:mm:dd hh:mm:ss
The Unknown
  • 19,224
  • 29
  • 77
  • 93

3 Answers3

10

See: Date/time conversion: string representation to time_t

And: [Boost-users] [date_time] So how come there isn't a to_time_t helper func?

So, apparently something like this should work:

#include <boost/date_time/posix_time/posix_time.hpp>
using namespace boost::posix_time;

std::string ts("2002-01-20 23:59:59");
ptime t(time_from_string(ts));
ptime start(gregorian::date(1970,1,1)); 
time_duration dur = t - start; 
time_t epoch = dur.total_seconds();    

But I don't think it's much cleaner than Rob's suggestion: use sscanf to parse the data into a struct tm and then call mktime.

Community
  • 1
  • 1
Reunanen
  • 7,921
  • 2
  • 35
  • 57
3

On Windows platform you can do something like this if don't want to use Boost:

// parsing string
SYSTEMTIME stime = { 0 };
sscanf(timeString, "%04d:%02d:%02d %02d:%02d:%02d",
       &stime.wYear, &stime.wMonth,  &stime.wDay,
       &stime.wHour, &stime.wMinute, &stime.wSecond);

// converting to utc file time
FILETIME lftime, ftime;
SystemTimeToFileTime(&stime, &lftime);
LocalFileTimeToFileTime(&lftime, &ftime);

// calculating seconds elapsed since 01/01/1601
// you can write similiar code to get time elapsed from other date
ULONGLONG elapsed = *(ULONGLONG*)&ftime / 10000000ull;

If you prefer standard library, you can use struct tm and mktime() to do the same job.

  • Btw, if you find yourself using sscanf for time strings into a struct tm, give strptime a look. It has some time-specific formats. For the above you could use "%Y:%m:%d %H:%M:%S" – Steve Jessop May 13 '09 at 16:57
1

http://www.boost.org/doc/libs/1_39_0/doc/html/date_time.html Should do the trick.

Chris Huang-Leaver
  • 6,059
  • 6
  • 41
  • 67
  • I was going to suggest this too -- ptime has time_from_string() to go from string to ptime -- but how to go from there to time_t ? – Reunanen May 13 '09 at 07:37
  • 1
    The problem with date_time is that a) you need the library (no header-only version) and b) no wstring support. – dirkgently May 13 '09 at 07:42