C++ How to change Time and Date

Filip 831 Reputation points
2021-04-09T18:32:01.203+00:00

Hello everybody.
Haw can i change time and date in c++?
Thanks for answare.

Developer technologies | C++
Developer technologies | C++
A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.
0 comments No comments
{count} votes

Answer accepted by question author
  1. Castorix31 91,511 Reputation points
    2021-04-09T19:10:45.68+00:00

    [cannot post code in comments : ridiculous limit of 1000 characters...]

    Tested on Windows 10 (1909) :

        SYSTEMTIME st;
        GetLocalTime(&st);
        st.wHour += 1;
    
        if (EnablePrivilege(GetCurrentProcess(), SE_SYSTEMTIME_NAME, TRUE))
        {
            BOOL bRet = SetLocalTime(&st);
            if (!bRet)
            {
                // Display code  for error message
            }
        }
    

    Function adapted from MSDN/SDK =>

    BOOL EnablePrivilege(HANDLE hprocess, LPWSTR privilege, BOOL flag)
    {
        HANDLE hToken = NULL;
        LUID DebugValue;
        TOKEN_PRIVILEGES tkp;
    
        if (!OpenProcessToken(hprocess,
            TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY,
            &hToken))
            goto errexit;
    
        if (!LookupPrivilegeValue((LPWSTR)NULL,
            privilege,
            &DebugValue))
            goto errexit;
    
        tkp.PrivilegeCount = 1;
        tkp.Privileges[0].Luid = DebugValue;
        if (flag)
            tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED |
            SE_PRIVILEGE_ENABLED_BY_DEFAULT |
            SE_PRIVILEGE_USED_FOR_ACCESS;
        else
            tkp.Privileges[0].Attributes = NULL;
    
        AdjustTokenPrivileges(hToken,
            FALSE,
            &tkp,
            sizeof(TOKEN_PRIVILEGES),
            (PTOKEN_PRIVILEGES)NULL,
            (PDWORD)NULL);
        DWORD nError = GetLastError();
        // ERROR_NOT_ALL_ASSIGNED 1300 (0x514)
    
        if (nError != ERROR_SUCCESS)
            goto errexit;
    
        CloseHandle(hToken);
        return TRUE;
    
    errexit:
        CloseHandle(hToken);
        return FALSE;
    }
    

1 additional answer

Sort by: Most helpful
  1. Castorix31 91,511 Reputation points
    2021-04-09T18:36:54.097+00:00

    Already answered : C++ set local pc time


Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.