Hello, I want to write auto-sync on Delphi

procedure TsinhForm.Button1Click(Sender: TObject); var ST : _SYSTEMTIME; begin ST.wYear := 2019; ST.wMonth := 5; ST.wDay := 14; ST.wHour := 8; ST.wMinute := 55; ST.wSecond := 59; SetSystemTime(ST); end; 

This is a permanent setting at the press of a button, and how when you press a button, using the IdSNTP tool, change the date / time?

    2 answers 2

    This component has a special SyncTime method that requests a date from the server and changes the system time if the server responds:

     uses IdSNTP; procedure SyncTime; var SNTPClient: TIdSNTP; begin SNTPClient := TIdSNTP.Create(nil); try SNTPClient.Host := 'pool.ntp.org'; SNTPClient.SyncTime; finally SNTPClient.Free; end; end; 
    • If I remember correctly, then the program should have admin rights, then the system will allow to change the time? - Vlad Chapl
    • @VladChapl In theory, yes, we need rights. But I work under the administrator and there is no place to check. In any case, the rights are needed exactly the same as in the case of manual setting the time when clicking on the button from the code in question. - zed
    • > I work under the administrator. In the latest versions of Windows (like starting with Vista) the admin is somewhat curtailed. Therefore, you need to specifically run "Run as administrator". Well, in the code to track OS error messages. (This is me to the case when the code "does not work".) - Vlad Chapl
    • @VladChapl I have Win8.1. The code from the answer was tested, the date / time changes without additional gestures. - zed

    If your Delphi-7 is not trimmed, then it has Indy. Otherwise, this set can be supplied - it is freely available. In subsequent versions of Delphi, it is present and quite useful at times.
    If I understand the question correctly, the implementation will be something like this:
    On the Indy Clients tab (sometimes just Indy ) there is a TIdSNTP component, we add it to the form, in the host property exposes the server we need (let it be 0.europe.pool.ntp.org ). Now your procedure will look like this:

     procedure TsinhForm.Button1Click(Sender: TObject); var ST : _SYSTEMTIME; y,m,d,h,mi,s,ms : word; dt:TDateTime; begin try dt:=IdSNTP1.DateTime; except //обрабатываем ошибки end; DecodeDate(dt,y,m,d); DecodeTime(dt, h, mi, s, ms); ST.wYear := y; ST.wMonth := m; ST.wDay := d; ST.wHour := h; ST.wMinute := mi; ST.wSecond := s; SetSystemTime(ST); end; 
    • What to do with "Socket Error # 11004"? - NickGrom
    • one
      @NickGrom Usually, the error in determining the server name. Either put the name together with the IP, or try another server - Viktor Tomilov
    • @NickGrom I have this error returned if I access the SNTP server via a proxy by name. If you do not use a proxy or use, but through IP, there is no error. - Alexey Kozlov