Search code examples
c++datetimeboostposix

convert Date to time in millisecond in c++?


I have a requirement where I have to convert given string in date time format to milliseconds from epoch. In Javascript there is date to time conversion api but in c++ I couldn't find anything as such.

Input would look like '2016-Mar-15 09:23:58.665068'

output should be in milliseconds say 14520000785.

I have tried looking into boost but still couldn't find(or understand) how to do? Also, going through google I find the other way round i.e. converting milliseconds to date format but not what I require nor any helpful post for same.

Any help will be much appreciated.


Solution

  • Most straightforward would be to just spell it out:

    auto pt = boost::lexical_cast<ptime>("2016-Mar-15 09:23:58.665068");
    std::cout << (pt - ptime { {1970,0,0}, {} }).total_milliseconds();
    

    Live On Coliru

    #include <boost/date_time/posix_time/posix_time.hpp>
    #include <boost/date_time/posix_time/posix_time_io.hpp>
    #include <boost/date_time.hpp>
    #include <sstream>
    
    int main() {
        using boost::posix_time::ptime;
    
        ptime pt;
        { 
            std::istringstream iss("2016-Mar-15 09:23:58.665068");
            auto* f = new boost::posix_time::time_input_facet("%Y-%b-%d %H:%M:%S%f");
    
            std::locale loc(std::locale(""), f);
            iss.imbue(loc);
            iss >> pt;
        }
    
        std::cout << pt << " " << (pt - ptime{{1970,1,1},{}}).total_milliseconds();
    }
    

    Prints

    2016-Mar-15 09:23:58.665068 1458033838665
    

    Of course, extract the parsing in a helper function. Keep the locale around for reuse etc.