Search code examples
c++classdecimalctime

Converting 13 decimals to datetime


I have a project about cars with GPS. I need to return the start and the finish moment for each car.

So we have:
time_t x, y; Because I will use later them for a transformation.

I have a problem. I read from an external file data in this format:

auto1
1439467747492 
auto1
1439467748512

...etc. auto1->name of the car;
1439467747492->the moment in time of the car

I tried to get the first position of the first moment and the last moment for each car. This is the code in C++:

 long test = momenti[choice1]/1000;
 time_t x = test;
 cout << "     Momentul initial:\n " << ctime(&x) << endl;
 long test1 = momentf[choice1] / 1000;
 time_t y = test1;
 cout << "     Momentul final:\n " << ctime(&y) << endl;

I receive the same date for every car. Is something like momenti[i]=momentf[i] What did I do wrong?


Solution

  • It is not good. According epoch converter we should get this : GMT: Thu, 13 Aug 2015 12:09:07 GMT

    Here is how you can get this output with C++11/14 and using this free, open source date library which extends the C++ <chrono> library to handle dates.

    #include "date.h"
    #include <chrono>
    #include <iostream>
    
    int
    main()
    {
        using namespace std::chrono;
        using namespace std;
        using namespace date;
        using time_point = std::chrono::time_point<system_clock, milliseconds>;
        auto tp = time_point{1439467747492ms};
        auto dp = floor<days>(tp);
        auto time = make_time(tp - dp);
        auto ymd = year_month_day{dp};
        cout << "GMT: " << weekday{dp} << ", " << ymd.day() << ' ' << ymd.month()
             << ' ' << ymd.year() << ' ' << time  << " GMT\n";
    }
    

    Output:

    GMT: Thu, 13 Aug 2015 12:09:07.492 GMT
    

    I threw in the fractional seconds for fun, and it seemed a shame to waste them (the C lib won't give them to you). If you really don't want them, it is easy to fix:

        auto time = make_time(floor<seconds>(tp) - dp);
    

    Now the output is:

    GMT: Thu, 13 Aug 2015 12:09:07 GMT
    

    You need C++14 for the 1439467747492ms above. If you only have C++11 you can sub in this instead: milliseconds{1439467747492}. If you only have C++03, then you are 13 years behind the times and stuck with ctime. ;-)

    The chrono solution will offer you greater type safety, more flexibility, and greater performance.

    If i can fix and the latitude and longitude problem would be great lol

    If you can translate latitude and longitude into an IANA timezone name (and there are tools to do this), I've got a IANA timezone database parser for you which interoperates with <chrono> and "date.h".