Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert current time from windows to unix timestamp in C or C++

First off, I know that this question was asked quite some times (although it seems that 90% are about converting Unix ts -> Windows). Secondly, I would add a comment to another accepted question where my problem would fit in instead of adding another one but I don't have enough reputation.

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 please just give a full working example for C or C++ without omitting such mad-driving details?

like image 606
Daniel Avatar asked Dec 04 '13 08:12

Daniel


1 Answers

And for people on Windows:

Int64 GetSystemTimeAsUnixTime()
{
   //Get the number of seconds since January 1, 1970 12:00am UTC
   //Code released into public domain; no attribution required.

   const Int64 UNIX_TIME_START = 0x019DB1DED53E8000; //January 1, 1970 (start of Unix epoch) in "ticks"
   const Int64 TICKS_PER_SECOND = 10000000; //a tick is 100ns

   FILETIME ft;
   GetSystemTimeAsFileTime(out ft); //returns ticks in UTC

   //Copy the low and high parts of FILETIME into a LARGE_INTEGER
   //This is so we can access the full 64-bits as an Int64 without causing an alignment fault
   LARGE_INTEGER li;
   li.LowPart  = ft.dwLowDateTime;
   li.HighPart = ft.dwHighDateTime;
 
   //Convert ticks since 1/1/1970 into seconds
   return (li.QuadPart - UNIX_TIME_START) / TICKS_PER_SECOND;
}

The name of the function matches the naming scheme used by other Windows functions. The Windows System Time is by definition UTC.

Function Return type Resolution
GetSystemTimeAsFileTime FILETIME struct 0.0000001 s
GetSystemTime SYSTEMTIME struct 0.001 s
GetSystemTimeAsUnixTime Int64 1 s
like image 101
Ian Boyd Avatar answered Sep 27 '22 22:09

Ian Boyd