Search code examples
c++posix

Convert Date-Time to Milliseconds - C++ - cross platform


I want to convert a string in the format of "20160907-05:00:54.123" into milliseconds. I know that strptime is not available in Windows and I want to run my program in both windows and linux. I can't use third party libraries as well. I can tokenize the string and convert it. But is there a more elegant way like using the strptime to do so?


Solution

  • Given the format of your string, it is fairly easy to parse it as follows (although a regex or get_time might be more elegant):

    tm t;
    t.tm_year = stoi(s.substr(0, 4));
    t.tm_mon = stoi(s.substr(4, 2));
    t.tm_mday = stoi(s.substr(6, 2));
    t.tm_hour = stoi(s.substr(9, 2));
    t.tm_min = stoi(s.substr(12, 2));
    t.tm_sec = 0;
    double sec = stod(s.substr(15));
    

    Finding the time since the epoch can be done with mktime:

    mktime(&t) + sec * 1000
    

    Note that the fractional seconds need to be handled differently - unfortunately, tm has only integer seconds.

    (See the full code here.)


    Edit

    As Mine and Panagiotis Kanavos correctly note in the comments, Visual C++ apparently supports get_time for quite a while, and it's much shorter with it (note that the fractional seconds need to be handled the same way, though).