Search code examples
c++winapisystemtime

win32 - How to use SYSTEMTIME structure as a countdown clock


Hey everyone I am using the structure SYSTEMTIME to perform arithematic with c++ to create a countdown timer. How would I set a custom time and make it countdown? This is a very generic question but if anyone who has experience with the SYSTEMTIME structure would be able to give me some assistance that would be very much appreciated!

  1. I want to set a default time for SYSTEMTIME so like

    SYSTEMTIME tvar;
    GetLocalTime(&tvar); // instead of using this to initiate the clock i'd like to set the time by myself
    

2. Also, how can I make this clock countdown from that time?

Take note that since I am using GDI it is necessary for me to use this structure and since the code that I already worked on with my group uses this structure we already have it implemented, so there is no room for changing, can anyone give me a solution to solve those two issues that I have?

!!! EDIT !!! I'm trying to recreate this timer here http://www.picksourcecode.com/ps/ct/161097.php in countdown format with just hours and minutes for a bomb timer for the adventure game that I am making with opengl. How would I reprogram this code so that I can incorporate a countdown digital clock of this standard?

Any help is appreciated, thanks so much!


Solution

  • The idea is fundamentally wrong. I would recommend to use FILETIME instead. The code should look like:

    typedef __int64 TDateTime;  // This is actually an alias to NT FILETIME.
    
    inline TDateTime  CurrDateTime()
    {
          TDateTime param;
          GetSystemTimeAsFileTime((FILETIME*)&param);
          return(param);
    }
    
    #define   ONE_SECOND    ((__int64)10000000)
    
    TDateTime myFinalTime = CurrDateTime() + 30*ONE_SECOND;
    while (CurrDateTime() < myFinalTime )
        Sleep(50);
    

    In fact FILETIME is a 64 bit integer. the function GetSystemTimeAsFileTime() is cheap. It works perfectly in the code like above. I used this many times.

    If you want to show the TDateTime value on the screen you need to call FileTimeToLocalFileTime(...) and then FileTimeToSystemTime(...) APIs.