Search code examples
c++unixtimeunix-timestamp

How to convert a Unix epoch time to a Pascal TDateTime(double) in C++


Following on from this Original post I need to do the conversion in the reverse direction (Unix Time to TDateTime).

@Howard Hinnant did a very elegant example using his date.h library but due to a compilation issue, I decided not to use it. His effort is appreciated though.

Could someone provide me with an example based on the code developed by @Remy Lebeau, please?


Solution

  • This direction is easier than the other one. Here is a way:

    #include <stdio.h>
    
    double UnixToDateTime(__int64 epoch)
    {
        int days = epoch / (24*3600);
        int secs = epoch % (24*3600);
        return 25569 + days + ((double)secs)/(24*3600);
    }
    
    int main()
    {
        printf("%.12f", UnixToDateTime(1060041720));
    }
    

    Output:

    37838.001388888886