c++cwindowsunixtime

Convert current time from Windows to Unix timestamp?


I saw the accepted solution in Convert Windows Filetime to second in Unix/Linux but am stuck at what I should pass to the function WindowsTickToUnixSeconds(). Judging by the parameter name windowsTicks I tried GetTickCount() but saw shortly after that this returns the ms since the system started but I need any reasonable count since the start of the Windows time (which seems to was in 1601?).

I saw that windows has a function for retrieving this time: GetSystemTime(). I cannot pass the resulting struct to the proposed function in 1 as it is not a long long value.

Can't someone just give a full working example for C or C++ without omitting such mad-driving details?


Solution

  • Maybe my question was phrased badly: All I wanted was to get the current time on a windows machine as a unix timestamp. I now figured it out myself (C language, Code::Blocks 12.11, Windows 7 64 bit):

    #include <stdio.h>
    #include <time.h>
    int main(int argc, char** argv) {
        time_t ltime;
        time(&ltime);
        printf("Current local time as unix timestamp: %li\n", ltime);
    
        struct tm* timeinfo = gmtime(&ltime); /* Convert to UTC */
        ltime = mktime(timeinfo); /* Store as unix timestamp */
        printf("Current UTC time as unix timestamp: %li\n", ltime);
    
        return 0;
    }
    

    Example output:

    Current local time as unix timestamp: 1386334692
    Current UTC time as unix timestamp: 1386331092