harry
harry

Reputation: 105

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.

Upvotes: 3

Views: 3267

Answers (2)

YSC
YSC

Reputation: 40150

Using only standard library features:

#include <ctime>
#include <chrono>
#include <iostream>

int main()
{
    std::tm tm = {};
    const char* snext = ::strptime("2016-Mar-15 09:23:58.665068", "%Y-%b-%d %H:%M:%S", &tm);
    auto time_point = std::chrono::system_clock::from_time_t(std::mktime(&tm));
    long long  duration_ms = time_point.time_since_epoch() / std::chrono::milliseconds(1) + std::atof(snext) * 1000.0f;
    std::cout << duration_ms << std::endl;
}

Prints: 1458033838665

See std::chrono::system_clock::now and std::chrono::milliseconds.

Upvotes: 3

sehe
sehe

Reputation: 393769

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.

Upvotes: 2

Related Questions