Skip to content

3.2 converting dmyhms to epoch seconds

Marshall Clow edited this page May 15, 2013 · 5 revisions

Problem

You want to convert YMDHMS to epoch seconds.

Solution:

Using Boost date-time this can be easily achieved.

#include <iostream>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <ctime>

using namespace boost::posix_time;
using namespace boost::gregorian;

// Missing function; will be part of Boost 1.54.0
std::time_t to_time_t (ptime pt) {
    time_duration dur = pt - ptime (date(1970,1,1));
    return dur.total_seconds ();
    }

// Helper function for creating boost::posix_time::ptime
ptime from_ymdhms ( int year, int month, int day, int hour, int minute, int sec ) {
    return ptime ( date ( year, month, day ), time_duration( hour, minute, sec ));
    }

int main ( int, char ** ) {
//  HMS -> epoch
    std::time_t t1 = to_time_t ( from_ymdhms ( 2013, 5, 13, 14, 10, 0 ));
    std::cout << "Epoch: " << t1 << std::endl;

    return 0;
    }

When you run this, you should get the output: Epoch: 1368454200

Clone this wiki locally