Programmatically getting system boot up time in c++ (windows)

You can also use WMI to get the precise time of boot. WMI is not for the faint of heart, but it will get you what you are looking for.

The information in question is on the Win32_OperatingSystem object under the LastBootUpTime property. You can examine other properties using WMI Tools.

WMI Explorer showing property instance

Edit: You can also get this information from the command line if you prefer.

wmic OS Get LastBootUpTime

As an example in C# it would look like the following (Using C++ it is rather verbose):

static void Main(string[] args)
{      
    // Create a query for OS objects
    SelectQuery query = new SelectQuery("Win32_OperatingSystem", "Status=\"OK\"");

    // Initialize an object searcher with this query
    ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);

    string dtString;
    // Get the resulting collection and loop through it
    foreach (ManagementObject envVar in searcher.Get())
        dtString = envVar["LastBootUpTime"].ToString();
}

GetTickCount64 "retrieves the number of milliseconds that have elapsed since the system was started."

Once you know how long the system has been running, it is simply a matter of subtracting this duration from the current time to determine when it was booted. For example, using the C++11 chrono library (supported by Visual C++ 2012):

auto uptime = std::chrono::milliseconds(GetTickCount64());
auto boot_time = std::chrono::system_clock::now() - uptime;

Tags:

Windows

C++

C