Jump to content

how to get the current date from the internet


Recommended Posts

#Include <StructureConstants.au3>
#Include <Date.au3>

Func _NTP_FT($sServer, $fLocal = True)

;~  http://book.itep.ru/4/44/sntp4416.htm

    Local $tNTP = DllStructCreate('byte Header[4];byte RootDelay[4];byte RootDispersion[4];byte ReferenceIdentifier[4];byte ReferenceTimestamp[8];byte OriginateTimestamp[8];byte ReceiveTimestamp[8];byte TransmitTimestamp[8];byte KeyIdentifier[4];byte MessageDigest[16]')
    Local $tPacket = DllStructCreate('byte Packet[68]', DllStructGetPtr($tNTP))
    Local $bPacket = 0, $tFT, $tQW, $aSocket, $aResult

;~  0x1B000000 = 00011011 00000000 00000000 00000000b (LI = 00b VN = 011b Mode = 011b Stratum = 00000000b Poll = 00000000b Precision = 00000000b)
    $tNTP.Header = Binary('0x1B000000')
    UDPStartup()
    If @Error Then
        Return SetError(1, 0, 0)
    EndIf
    $aSocket = UDPOpen(TCPNameToIP($sServer), 123)
    If @Error Then
        ; Nothing
    Else
        UDPSend($aSocket, $tPacket.Packet)
        If @Error Then
            ; Nothing
        Else
            While 1
                $bPacket = UDPRecv($aSocket, 68, 1)
                If (@Error) Or ($bPacket) Then
                    ExitLoop
                EndIf
                Sleep(100)
            WEnd
        EndIf
    EndIf
    UDPCloseSocket($aSocket)
    UDPShutdown()
    If Not $bPacket Then
        Return SetError(2, 0, 0)
    EndIf
    $tFT = DllStructCreate($tagFILETIME)
    If $fLocal Then
        $tQW = DllStructCreate('uint64 Timestamp')
    Else
        $tQW = DllStructCreate('uint64 Timestamp', DllStructGetPtr($tFT))
    EndIf
    $tPacket.Packet = $bPacket
ConsoleWrite($bPacket & @CRLF)
    $tQW.Timestamp = Dec(StringMid(DllStructGetData($tNTP, 'TransmitTimestamp'), 3, 8), 2) * 10000000 + 94354848000000000
ConsoleWrite(Dec(StringMid(DllStructGetData($tNTP, 'TransmitTimestamp'), 3, 8), 2) & @CRLF)
    If $fLocal Then
        $aResult = DllCall('kernel32.dll', 'bool', 'FileTimeToLocalFileTime', 'struct*', $tQW, "struct*", $tFT)
        If (@Error) Or (Not $aResult[0]) Then
            Return SetError(3, 0, 0)
        EndIf
    EndIf
    Return $tFT
EndFunc   ;==>_NTP_FT

$tFT = _NTP_FT('pool.ntp.org')

ConsoleWrite(_Date_Time_FileTimeToStr($tFT) & @CRLF)
 

0x1C0100ED000000000000001450505300D8C63C4D731DB4060000000000000000D8C63C52CDD5AE56D8C63C52CDD827A800000000
3636870226
04/01/2015 12:43:46
Link to comment
Share on other sites

I added @error to consolewrite

$tFT = _NTP_FT('pool.ntp.org')
ConsoleWrite('@error = ' & @error & @CR)
ConsoleWrite(_Date_Time_FileTimeToStr($tFT) & @CRLF)

 

0x1C0303EC0000024800003447C3BBF537D8C63D14477201FB0000000000000000D8C63D4E2F3B6889D8C63D4E2F43A16800000000

1
@error = 0
01/01/1900 02:00:01
 

Signature beginning:
Please remember: "AutoIt"..... *  Wondering who uses AutoIt and what it can be used for ? * Forum Rules *
ADO.au3 UDF * POP3.au3 UDF * XML.au3 UDF * IE on Windows 11 * How to ask ChatGPT for AutoIt Codefor other useful stuff click the following button:

Spoiler

Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind. 

My contribution (my own projects): * Debenu Quick PDF Library - UDF * Debenu PDF Viewer SDK - UDF * Acrobat Reader - ActiveX Viewer * UDF for PDFCreator v1.x.x * XZip - UDF * AppCompatFlags UDF * CrowdinAPI UDF * _WinMergeCompare2Files() * _JavaExceptionAdd() * _IsBeta() * Writing DPI Awareness App - workaround * _AutoIt_RequiredVersion() * Chilkatsoft.au3 UDF * TeamViewer.au3 UDF * JavaManagement UDF * VIES over SOAP * WinSCP UDF * GHAPI UDF - modest begining - comunication with GitHub REST APIErrorLog.au3 UDF - A logging Library * Include Dependency Tree (Tool for analyzing script relations) * Show_Macro_Values.au3 *

 

My contribution to others projects or UDF based on  others projects: * _sql.au3 UDF  * POP3.au3 UDF *  RTF Printer - UDF * XML.au3 UDF * ADO.au3 UDF SMTP Mailer UDF * Dual Monitor resolution detection * * 2GUI on Dual Monitor System * _SciLexer.au3 UDF * SciTE - Lexer for console pane

Useful links: * Forum Rules * Forum etiquette *  Forum Information and FAQs * How to post code on the forum * AutoIt Online Documentation * AutoIt Online Beta Documentation * SciTE4AutoIt3 getting started * Convert text blocks to AutoIt code * Games made in Autoit * Programming related sites * Polish AutoIt Tutorial * DllCall Code Generator * 

Wiki: Expand your knowledge - AutoIt Wiki * Collection of User Defined Functions * How to use HelpFile * Good coding practices in AutoIt * 

OpenOffice/LibreOffice/XLS Related: WriterDemo.au3 * XLS/MDB from scratch with ADOX

IE Related:  * How to use IE.au3  UDF with  AutoIt v3.3.14.x * Why isn't Autoit able to click a Javascript Dialog? * Clicking javascript button with no ID * IE document >> save as MHT file * IETab Switcher (by LarsJ ) * HTML Entities * _IEquerySelectorAll() (by uncommon) * IE in TaskSchedulerIE Embedded Control Versioning (use IE9+ and HTML5 in a GUI) * PDF Related:How to get reference to PDF object embeded in IE * IE on Windows 11

I encourage you to read: * Global Vars * Best Coding Practices * Please explain code used in Help file for several File functions * OOP-like approach in AutoIt * UDF-Spec Questions *  EXAMPLE: How To Catch ConsoleWrite() output to a file or to CMD *

I also encourage you to check awesome @trancexx code:  * Create COM objects from modules without any demand on user to register anything. * Another COM object registering stuffOnHungApp handlerAvoid "AutoIt Error" message box in unknown errors  * HTML editor

winhttp.au3 related : * https://www.autoitscript.com/forum/topic/206771-winhttpau3-download-problem-youre-speaking-plain-http-to-an-ssl-enabled-server-port/

"Homo sum; humani nil a me alienum puto" - Publius Terentius Afer
"Program are meant to be read by humans and only incidentally for computers and execute" - Donald Knuth, "The Art of Computer Programming"
:naughty:  :ranting:, be  :) and       \\//_.

Anticipating Errors :  "Any program that accepts data from a user must include code to validate that data before sending it to the data store. You cannot rely on the data store, ...., or even your programming language to notify you of problems. You must check every byte entered by your users, making sure that data is the correct type for its field and that required fields are not empty."

Signature last update: 2023-04-24

Link to comment
Share on other sites

The problem with Dec() or StringMid(). You need to retrieve 0xD8C63D4E as UINT.

0x1C0303EC0000024800003447C3BBF537D8C63D14477201FB0000000000000000D8C63D4E2F3B6889D8C63D4E2F43A16800000000

Edited by Yashied
Link to comment
Share on other sites

Au3.3.13.20

 

0x1C0203E9000005D60000085E82951115D8C63FB8841140910000000000000000D8C63FF0F79A7594D8C63FF0F79D618B00000000

3636871152
@error = 0
04/01/2015 11:59:12

 

and sometime I get:

 

@error = 2

 

and empty string 

But as I see this is connection problem.

 

I think it is time to jump in Au3.3.12.0 instead 3.3.10.2

:)

Thanks.

mLipok

Signature beginning:
Please remember: "AutoIt"..... *  Wondering who uses AutoIt and what it can be used for ? * Forum Rules *
ADO.au3 UDF * POP3.au3 UDF * XML.au3 UDF * IE on Windows 11 * How to ask ChatGPT for AutoIt Codefor other useful stuff click the following button:

Spoiler

Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind. 

My contribution (my own projects): * Debenu Quick PDF Library - UDF * Debenu PDF Viewer SDK - UDF * Acrobat Reader - ActiveX Viewer * UDF for PDFCreator v1.x.x * XZip - UDF * AppCompatFlags UDF * CrowdinAPI UDF * _WinMergeCompare2Files() * _JavaExceptionAdd() * _IsBeta() * Writing DPI Awareness App - workaround * _AutoIt_RequiredVersion() * Chilkatsoft.au3 UDF * TeamViewer.au3 UDF * JavaManagement UDF * VIES over SOAP * WinSCP UDF * GHAPI UDF - modest begining - comunication with GitHub REST APIErrorLog.au3 UDF - A logging Library * Include Dependency Tree (Tool for analyzing script relations) * Show_Macro_Values.au3 *

 

My contribution to others projects or UDF based on  others projects: * _sql.au3 UDF  * POP3.au3 UDF *  RTF Printer - UDF * XML.au3 UDF * ADO.au3 UDF SMTP Mailer UDF * Dual Monitor resolution detection * * 2GUI on Dual Monitor System * _SciLexer.au3 UDF * SciTE - Lexer for console pane

Useful links: * Forum Rules * Forum etiquette *  Forum Information and FAQs * How to post code on the forum * AutoIt Online Documentation * AutoIt Online Beta Documentation * SciTE4AutoIt3 getting started * Convert text blocks to AutoIt code * Games made in Autoit * Programming related sites * Polish AutoIt Tutorial * DllCall Code Generator * 

Wiki: Expand your knowledge - AutoIt Wiki * Collection of User Defined Functions * How to use HelpFile * Good coding practices in AutoIt * 

OpenOffice/LibreOffice/XLS Related: WriterDemo.au3 * XLS/MDB from scratch with ADOX

IE Related:  * How to use IE.au3  UDF with  AutoIt v3.3.14.x * Why isn't Autoit able to click a Javascript Dialog? * Clicking javascript button with no ID * IE document >> save as MHT file * IETab Switcher (by LarsJ ) * HTML Entities * _IEquerySelectorAll() (by uncommon) * IE in TaskSchedulerIE Embedded Control Versioning (use IE9+ and HTML5 in a GUI) * PDF Related:How to get reference to PDF object embeded in IE * IE on Windows 11

I encourage you to read: * Global Vars * Best Coding Practices * Please explain code used in Help file for several File functions * OOP-like approach in AutoIt * UDF-Spec Questions *  EXAMPLE: How To Catch ConsoleWrite() output to a file or to CMD *

I also encourage you to check awesome @trancexx code:  * Create COM objects from modules without any demand on user to register anything. * Another COM object registering stuffOnHungApp handlerAvoid "AutoIt Error" message box in unknown errors  * HTML editor

winhttp.au3 related : * https://www.autoitscript.com/forum/topic/206771-winhttpau3-download-problem-youre-speaking-plain-http-to-an-ssl-enabled-server-port/

"Homo sum; humani nil a me alienum puto" - Publius Terentius Afer
"Program are meant to be read by humans and only incidentally for computers and execute" - Donald Knuth, "The Art of Computer Programming"
:naughty:  :ranting:, be  :) and       \\//_.

Anticipating Errors :  "Any program that accepts data from a user must include code to validate that data before sending it to the data store. You cannot rely on the data store, ...., or even your programming language to notify you of problems. You must check every byte entered by your users, making sure that data is the correct type for its field and that required fields are not empty."

Signature last update: 2023-04-24

Link to comment
Share on other sites

#Include <Date.au3>
#Include <StructureConstants.au3>
#Include <WinAPIMisc.au3>

Func _NTP_FT($sServer, $fLocal = True)

;~  http://book.itep.ru/4/44/sntp4416.htm

    Local $tNTP = DllStructCreate('byte Header[4];byte RootDelay[4];byte RootDispersion[4];byte ReferenceIdentifier[4];byte ReferenceTimestamp[8];byte OriginateTimestamp[8];byte ReceiveTimestamp[8];byte TransmitTimestamp[8];byte KeyIdentifier[4];byte MessageDigest[16]')
    Local $tPacket = DllStructCreate('byte Packet[68]', DllStructGetPtr($tNTP))
    Local $bPacket = 0, $tFT, $tQW, $aSocket, $aResult

;~  0x1B000000 = 00011011 00000000 00000000 00000000b (LI = 00b VN = 011b Mode = 011b Stratum = 00000000b Poll = 00000000b Precision = 00000000b)
    $tNTP.Header = Binary('0x1B000000')
    UDPStartup()
    If @Error Then
        Return SetError(1, 0, 0)
    EndIf
    $aSocket = UDPOpen(TCPNameToIP($sServer), 123)
    If @Error Then
        ; Nothing
    Else
        UDPSend($aSocket, $tPacket.Packet)
        If @Error Then
            ; Nothing
        Else
            While 1
                $bPacket = UDPRecv($aSocket, 68, 1)
                If (@Error) Or ($bPacket) Then
                    ExitLoop
                EndIf
                Sleep(100)
            WEnd
        EndIf
    EndIf
    UDPCloseSocket($aSocket)
    UDPShutdown()
    If Not $bPacket Then
        Return SetError(2, 0, 0)
    EndIf
    $tFT = DllStructCreate($tagFILETIME)
    If $fLocal Then
        $tQW = DllStructCreate('uint64 Timestamp')
    Else
        $tQW = DllStructCreate('uint64 Timestamp', DllStructGetPtr($tFT))
    EndIf
    $tPacket.Packet = $bPacket
    $tQW.Timestamp = _WinAPI_SwapDWord(DllStructGetData(DllStructCreate('uint', DllStructGetPtr($tNTP, 'TransmitTimestamp')), 1)) * 10000000 + 94354848000000000
    If $fLocal Then
        $aResult = DllCall('kernel32.dll', 'bool', 'FileTimeToLocalFileTime', 'struct*', $tQW, "struct*", $tFT)
        If (@Error) Or (Not $aResult[0]) Then
            Return SetError(3, 0, 0)
        EndIf
    EndIf
    Return $tFT
EndFunc   ;==>_NTP_FT

$tFT = _NTP_FT('pool.ntp.org')

ConsoleWrite(_Date_Time_FileTimeToStr($tFT) & @CRLF)

Link to comment
Share on other sites

Fixed :)

thanks.

mLipok

Signature beginning:
Please remember: "AutoIt"..... *  Wondering who uses AutoIt and what it can be used for ? * Forum Rules *
ADO.au3 UDF * POP3.au3 UDF * XML.au3 UDF * IE on Windows 11 * How to ask ChatGPT for AutoIt Codefor other useful stuff click the following button:

Spoiler

Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind. 

My contribution (my own projects): * Debenu Quick PDF Library - UDF * Debenu PDF Viewer SDK - UDF * Acrobat Reader - ActiveX Viewer * UDF for PDFCreator v1.x.x * XZip - UDF * AppCompatFlags UDF * CrowdinAPI UDF * _WinMergeCompare2Files() * _JavaExceptionAdd() * _IsBeta() * Writing DPI Awareness App - workaround * _AutoIt_RequiredVersion() * Chilkatsoft.au3 UDF * TeamViewer.au3 UDF * JavaManagement UDF * VIES over SOAP * WinSCP UDF * GHAPI UDF - modest begining - comunication with GitHub REST APIErrorLog.au3 UDF - A logging Library * Include Dependency Tree (Tool for analyzing script relations) * Show_Macro_Values.au3 *

 

My contribution to others projects or UDF based on  others projects: * _sql.au3 UDF  * POP3.au3 UDF *  RTF Printer - UDF * XML.au3 UDF * ADO.au3 UDF SMTP Mailer UDF * Dual Monitor resolution detection * * 2GUI on Dual Monitor System * _SciLexer.au3 UDF * SciTE - Lexer for console pane

Useful links: * Forum Rules * Forum etiquette *  Forum Information and FAQs * How to post code on the forum * AutoIt Online Documentation * AutoIt Online Beta Documentation * SciTE4AutoIt3 getting started * Convert text blocks to AutoIt code * Games made in Autoit * Programming related sites * Polish AutoIt Tutorial * DllCall Code Generator * 

Wiki: Expand your knowledge - AutoIt Wiki * Collection of User Defined Functions * How to use HelpFile * Good coding practices in AutoIt * 

OpenOffice/LibreOffice/XLS Related: WriterDemo.au3 * XLS/MDB from scratch with ADOX

IE Related:  * How to use IE.au3  UDF with  AutoIt v3.3.14.x * Why isn't Autoit able to click a Javascript Dialog? * Clicking javascript button with no ID * IE document >> save as MHT file * IETab Switcher (by LarsJ ) * HTML Entities * _IEquerySelectorAll() (by uncommon) * IE in TaskSchedulerIE Embedded Control Versioning (use IE9+ and HTML5 in a GUI) * PDF Related:How to get reference to PDF object embeded in IE * IE on Windows 11

I encourage you to read: * Global Vars * Best Coding Practices * Please explain code used in Help file for several File functions * OOP-like approach in AutoIt * UDF-Spec Questions *  EXAMPLE: How To Catch ConsoleWrite() output to a file or to CMD *

I also encourage you to check awesome @trancexx code:  * Create COM objects from modules without any demand on user to register anything. * Another COM object registering stuffOnHungApp handlerAvoid "AutoIt Error" message box in unknown errors  * HTML editor

winhttp.au3 related : * https://www.autoitscript.com/forum/topic/206771-winhttpau3-download-problem-youre-speaking-plain-http-to-an-ssl-enabled-server-port/

"Homo sum; humani nil a me alienum puto" - Publius Terentius Afer
"Program are meant to be read by humans and only incidentally for computers and execute" - Donald Knuth, "The Art of Computer Programming"
:naughty:  :ranting:, be  :) and       \\//_.

Anticipating Errors :  "Any program that accepts data from a user must include code to validate that data before sending it to the data store. You cannot rely on the data store, ...., or even your programming language to notify you of problems. You must check every byte entered by your users, making sure that data is the correct type for its field and that required fields are not empty."

Signature last update: 2023-04-24

Link to comment
Share on other sites

  • 10 months later...

My latest modifications:

#include <Date.au3>
#include <StructureConstants.au3>
#include <WinAPIMisc.au3>

; #FUNCTION# ====================================================================================================================
; Name ..........: _NTP_FT
; Description ...: Get Time from NTP Server
; Syntax ........: _NTP_FT($sServer[, $fLocal = True])
; Parameters ....: $sServer             - a string value.
;                  $fLocal              - [optional] a floating point value. Default is True.
; Return values .: NTP Time
; Author ........: Yashied
; Modified ......:
; Remarks .......:
; Related .......: http://book.itep.ru/4/44/sntp4416.htm
; Link ..........: https://www.autoitscript.com/forum/topic/169356-how-to-get-the-current-date-from-the-internet/
; Example .......: No
; ===============================================================================================================================
Func _NTP_FT($sServer, $fLocal = True)

    Local $tNTP = DllStructCreate('byte Header[4];byte RootDelay[4];byte RootDispersion[4];byte ReferenceIdentifier[4];byte ReferenceTimestamp[8];byte OriginateTimestamp[8];byte ReceiveTimestamp[8];byte TransmitTimestamp[8];byte KeyIdentifier[4];byte MessageDigest[16]')
    Local $tPacket = DllStructCreate('byte Packet[68]', DllStructGetPtr($tNTP))
    Local $bPacket = 0, $tFT, $tQW, $aSocket, $aResult

;~  0x1B000000 = 00011011 00000000 00000000 00000000b (LI = 00b VN = 011b Mode = 011b Stratum = 00000000b Poll = 00000000b Precision = 00000000b)
    $tNTP.Header = Binary('0x1B000000')
    UDPStartup()
    If @error Then
        Return SetError(1, 0, 0)
    EndIf
    $aSocket = UDPOpen(TCPNameToIP($sServer), 123)
    If @error Then
        ; Nothing
    Else
        UDPSend($aSocket, $tPacket.Packet)
        If @error Then
            ; Nothing
        Else
            While 1
                $bPacket = UDPRecv($aSocket, 68, 1)
                If (@error) Or ($bPacket) Then
                    ExitLoop
                EndIf
                Sleep(100)
            WEnd
        EndIf
    EndIf
    UDPCloseSocket($aSocket)
    UDPShutdown()
    If Not $bPacket Then
        Return SetError(2, 0, 0)
    EndIf

    $tFT = DllStructCreate($tagFILETIME)
    If $fLocal Then
        $tQW = DllStructCreate('uint64 Timestamp')
    Else
        $tQW = DllStructCreate('uint64 Timestamp', DllStructGetPtr($tFT))
    EndIf
    $tPacket.Packet = $bPacket
    $tQW.Timestamp = _WinAPI_SwapDWord(DllStructGetData(DllStructCreate('uint', DllStructGetPtr($tNTP, 'TransmitTimestamp')), 1)) * 10000000 + 94354848000000000
    If $fLocal Then
        $aResult = DllCall('kernel32.dll', 'bool', 'FileTimeToLocalFileTime', 'struct*', $tQW, "struct*", $tFT)
        If (@error) Or (Not $aResult[0]) Then
            Return SetError(3, 0, 0)
        EndIf
    EndIf
    Return SetError(0, 0, $tFT)
EndFunc    ;==>_NTP_FT

; #FUNCTION# ====================================================================================================================
; Name ..........: _NTP_GetTime_PL
; Description ...:
; Syntax ........: _NTP_GetTime_PL([$sNTP_Server = 'pool.ntp.org'])
; Parameters ....: $sNTP_Server         - [optional] a string value. Default is 'pool.ntp.org'.
; Return values .: NTP Time
; Author ........: Yashied
; Modified ......: mLipok (PL Version)
; Remarks .......:
; Related .......:
; Link ..........: https://www.autoitscript.com/forum/topic/169356-how-to-get-the-current-date-from-the-internet/
; Example .......: No
; ===============================================================================================================================
Func _NTP_GetTime_PL($sNTP_Server = 'pool.ntp.org')
    Local $tFT = _NTP_FT($sNTP_Server)
    If @error Then
        Return SetError(1, @error, '')
    Else
        Local $sTime = _Date_Time_FileTimeToStr($tFT, 1)
        Return SetError(0, 0, $sTime)
    EndIf
EndFunc    ;==>_NTP_GetTime_PL

; #FUNCTION# ====================================================================================================================
; Name ..........: _NTP_GetTime_PLServers
; Description ...: Function for pickup PL current time, alternately from different servers
; Syntax ........: _NTP_GetTime_PLServers()
; Parameters ....: Time
; Return values .: None
; Author ........: mLipok
; Modified ......:
; Remarks .......: https://pl.wikipedia.org/wiki/Serwer_czasu
; Related .......:
; Link ..........: https://www.autoitscript.com/forum/topic/169356-how-to-get-the-current-date-from-the-internet/?page=2
; Example .......: No
; ===============================================================================================================================
Func _NTP_GetTime_PLServers()
    Local $sNTP_Time, $sNTP_Server = ''
    Local Static $sNTP_Server_Last = ''
    
    Local $aNTP_Servers = _
            [ _
            '0.pl.pool.ntp.org', _  ; http://www.pool.ntp.org/zone/pl
            '1.pl.pool.ntp.org', _  ; http://www.pool.ntp.org/zone/pl
            '2.pl.pool.ntp.org', _  ; http://www.pool.ntp.org/zone/pl
            '3.pl.pool.ntp.org', _  ; http://www.pool.ntp.org/zone/pl
            'tempus1.gum.gov.pl', _ ; https://www.gum.gov.pl/pl/zegar/
            'tempus2.gum.gov.pl', _ ; https://www.gum.gov.pl/pl/zegar/
            'ntp1.tp.pl', _  ; (źródło: atomowy zegar cezowy 5071A TP S.A.)
            'ntp2.tp.pl', _  ; (źródło: atomowy zegar cezowy 5071A TP S.A.)
            'ntp.icm.edu.pl', _  ; http://icm.edu.pl/web/guest
            'ntp.certum.pl', _  ; certum.pl
            'pool.ntp.org' _
            ]

    While 1
        $sNTP_Server = $aNTP_Servers[Random(0, UBound($aNTP_Servers) - 1, 1)]
        If $sNTP_Server = $sNTP_Server_Last Then
            ContinueLoop
        Else
            $sNTP_Server_Last = $sNTP_Server
        EndIf

        $sNTP_Time = _NTP_GetTime_PL($sNTP_Server)
        If Not @error Then ExitLoop
        Sleep(10)
    WEnd

    Return $sNTP_Time

EndFunc   ;==>_NTP_GetTime_PL

 

Signature beginning:
Please remember: "AutoIt"..... *  Wondering who uses AutoIt and what it can be used for ? * Forum Rules *
ADO.au3 UDF * POP3.au3 UDF * XML.au3 UDF * IE on Windows 11 * How to ask ChatGPT for AutoIt Codefor other useful stuff click the following button:

Spoiler

Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind. 

My contribution (my own projects): * Debenu Quick PDF Library - UDF * Debenu PDF Viewer SDK - UDF * Acrobat Reader - ActiveX Viewer * UDF for PDFCreator v1.x.x * XZip - UDF * AppCompatFlags UDF * CrowdinAPI UDF * _WinMergeCompare2Files() * _JavaExceptionAdd() * _IsBeta() * Writing DPI Awareness App - workaround * _AutoIt_RequiredVersion() * Chilkatsoft.au3 UDF * TeamViewer.au3 UDF * JavaManagement UDF * VIES over SOAP * WinSCP UDF * GHAPI UDF - modest begining - comunication with GitHub REST APIErrorLog.au3 UDF - A logging Library * Include Dependency Tree (Tool for analyzing script relations) * Show_Macro_Values.au3 *

 

My contribution to others projects or UDF based on  others projects: * _sql.au3 UDF  * POP3.au3 UDF *  RTF Printer - UDF * XML.au3 UDF * ADO.au3 UDF SMTP Mailer UDF * Dual Monitor resolution detection * * 2GUI on Dual Monitor System * _SciLexer.au3 UDF * SciTE - Lexer for console pane

Useful links: * Forum Rules * Forum etiquette *  Forum Information and FAQs * How to post code on the forum * AutoIt Online Documentation * AutoIt Online Beta Documentation * SciTE4AutoIt3 getting started * Convert text blocks to AutoIt code * Games made in Autoit * Programming related sites * Polish AutoIt Tutorial * DllCall Code Generator * 

Wiki: Expand your knowledge - AutoIt Wiki * Collection of User Defined Functions * How to use HelpFile * Good coding practices in AutoIt * 

OpenOffice/LibreOffice/XLS Related: WriterDemo.au3 * XLS/MDB from scratch with ADOX

IE Related:  * How to use IE.au3  UDF with  AutoIt v3.3.14.x * Why isn't Autoit able to click a Javascript Dialog? * Clicking javascript button with no ID * IE document >> save as MHT file * IETab Switcher (by LarsJ ) * HTML Entities * _IEquerySelectorAll() (by uncommon) * IE in TaskSchedulerIE Embedded Control Versioning (use IE9+ and HTML5 in a GUI) * PDF Related:How to get reference to PDF object embeded in IE * IE on Windows 11

I encourage you to read: * Global Vars * Best Coding Practices * Please explain code used in Help file for several File functions * OOP-like approach in AutoIt * UDF-Spec Questions *  EXAMPLE: How To Catch ConsoleWrite() output to a file or to CMD *

I also encourage you to check awesome @trancexx code:  * Create COM objects from modules without any demand on user to register anything. * Another COM object registering stuffOnHungApp handlerAvoid "AutoIt Error" message box in unknown errors  * HTML editor

winhttp.au3 related : * https://www.autoitscript.com/forum/topic/206771-winhttpau3-download-problem-youre-speaking-plain-http-to-an-ssl-enabled-server-port/

"Homo sum; humani nil a me alienum puto" - Publius Terentius Afer
"Program are meant to be read by humans and only incidentally for computers and execute" - Donald Knuth, "The Art of Computer Programming"
:naughty:  :ranting:, be  :) and       \\//_.

Anticipating Errors :  "Any program that accepts data from a user must include code to validate that data before sending it to the data store. You cannot rely on the data store, ...., or even your programming language to notify you of problems. You must check every byte entered by your users, making sure that data is the correct type for its field and that required fields are not empty."

Signature last update: 2023-04-24

Link to comment
Share on other sites

That _NTP_FT function seems not to work behind a proxy.

I use this function to get the date which should be accurate.

#include <Array.au3>
Global $iError = 0, $oErrorChk = ObjEvent("AutoIt.Error", "ObjErrChk")

$aResult = GetDateFromINet()
If @error Then
    ConsoleWrite("Error connecting to internet!" & @CRLF)
Else
    _ArrayDisplay($aResult)
EndIf

Func GetDateFromINet($bProxy = False, $sProxy = "", $sURL = "http://www.google.com/")
    Local $oHTTP = ObjCreate("winhttp.winhttprequest.5.1")
    If $iError Then Return SetError(1, 0, 0)
    If $bProxy Then $oHttp.SetProxy(2, $sProxy)
    $oHTTP.Open("GET", $sURL, False)
    $oHTTP.Send()
    If $iError Then Return SetError(2, 0, 0)
    Local $sDate = $oHTTP.GetResponseHeader("Date")
    Local $sYear = StringRegExpReplace($sDate, ".+,\s*\d+\s*\w+\s*(20\d+)\s*.*", "$1")
    Local $iMonth, $aMonth[13] = [12, "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dez"]
    $iMonth = _ArraySearch($aMonth, StringRegExpReplace($sDate, ".+,\s*\d+\s*(\w+)\s*20\d+\s*.*", "$1"))
    Local $iDay, $aDay[8] = [7, "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
    $iDay = StringRegExpReplace($sDate, ".+,\s*(\d+)\s*\w+\s*20\d+\s*.*", "$1")
    $oHTTP = Null
    Local $aDate[3] = [$sYear, StringFormat("%02i", $iMonth), StringFormat("%02i", $iDay)]
    Return $aDate
EndFunc

Func ObjErrChk()
    $iError += 1
    ConsoleWrite($oErrorChk.scriptline & @CRLF)
    ConsoleWrite($oErrorChk.windescription & @CRLF)
    ConsoleWrite($oErrorChk.number & " / " & Hex($oErrorChk.number) & @CRLF)
EndFunc

 

Edited by UEZ

Please don't send me any personal message and ask for support! I will not reply!

Selection of finest graphical examples at Codepen.io

The own fart smells best!
Her 'sikim hıyar' diyene bir avuç tuz alıp koşma!
¯\_(ツ)_/¯  ٩(●̮̮̃•̃)۶ ٩(-̮̮̃-̃)۶ૐ

Link to comment
Share on other sites

  • 5 years later...

I have a function that gets the time from the internet, i.e. it uses NTP servers.
Sometimes, however, this function can be called several thousand times in a single data processing process that takes, say, an hour.

I wonder if it will be enough if I get the time using NTP, and then for the next specified time interval I will use TimerDiff () and then again after this interval, I will repeat the query of the NTP server.

And now I wondering  about  TimerDiff() usage because of:


https://www.autoitscript.com/autoit3/docs/functions/TimerDiff.htm

Quote

Remarks

Some processors are known to cause the function to return incorrect result.

 

Do these processor imperfections matter if I am going to refresh my time every 5 minutes by downloading it from the NTP server?

 

Here is my modified _NTP_GetTime_PLServers() function:

; #FUNCTION# ====================================================================================================================
; Name ..........: _NTP_GetTime_PLServers
; Description ...: Function for pickup PL current time, alternately from different servers
; Syntax ........: _NTP_GetTime_PLServers()
; Parameters ....: none
; Return values .: NTP Time
; Author ........: mLipok
; Modified ......:
; Remarks .......: https://pl.wikipedia.org/wiki/Serwer_czasu
; Related .......:
; Link ..........: https://www.autoitscript.com/forum/topic/169356-how-to-get-the-current-date-from-the-internet/?page=2
; Example .......: No
; ===============================================================================================================================
Func _NTP_GetTime_PLServers()

    Local Const $aNTP_Servers = _
            [ _
            'time.windows.com', _ ; standardowy serwer czasu WINDOWS
            'ntp1.tp.pl', _ ; (źródło: atomowy zegar cezowy 5071A TP S.A.)
            'ntp2.tp.pl', _ ; (źródło: atomowy zegar cezowy 5071A TP S.A.)
            'ntp.icm.edu.pl', _ ; http://icm.edu.pl/web/guest
            'ntp.certum.pl', _ ; certum.pl
            'pool.ntp.org', _
            'time.coi.pw.edu.pl', _ ; https://pl.wikipedia.org/wiki/Serwer_czasu
            'ntp.nask.pl', _ ; https://pl.wikipedia.org/wiki/Serwer_czasu
            'ntp.task.gda.pl', _ ; https://pl.wikipedia.org/wiki/Serwer_czasu
            'news-archive.icm.edu.pl', _ ; https://pl.wikipedia.org/wiki/Serwer_czasu
            '0.pl.pool.ntp.org', _ ; http://www.pool.ntp.org/zone/pl
            '1.pl.pool.ntp.org', _ ; http://www.pool.ntp.org/zone/pl
            '2.pl.pool.ntp.org', _ ; http://www.pool.ntp.org/zone/pl
            '3.pl.pool.ntp.org', _ ; http://www.pool.ntp.org/zone/pl
            'ntp.media-com.com.pl', _ ; Bieruń > W.T.
            'tempus1.gum.gov.pl', _ ; https://www.gum.gov.pl/pl/zegar/
            'tempus2.gum.gov.pl' _ ; https://www.gum.gov.pl/pl/zegar/
            ]

    Local Static $sNTP_Time_Static
    #Region - _NTP_GetTime_PLServers() - checking interval
    Local Const $iTIMER_INTERVAL_SECONDS = 30 ;
    Local Static $hTimer = TimerInit()
    Local $iSecondsPastAway = Round(TimerDiff($hTimer) / 1000)
    If Not @Compiled Then ConsoleWrite("+ " & @ScriptLineNumber & ' :: ' & $iSecondsPastAway & ' / ' & $iTIMER_INTERVAL_SECONDS & ' >>> ' & _DateAdd('s', $iSecondsPastAway, $sNTP_Time_Static) & @CRLF)

    If $sNTP_Time_Static And $iSecondsPastAway <= $iTIMER_INTERVAL_SECONDS Then
        Return _DateAdd('s', $iSecondsPastAway, $sNTP_Time_Static)
    EndIf
    #EndRegion - _NTP_GetTime_PLServers() - checking interval

    #Region - _NTP_GetTime_PLServers() - checking internet time
    Local Const $i_NTP_Server_Count = UBound($aNTP_Servers)
    Local Static $i_NTP_Server_IDX = 0
    If $i_NTP_Server_IDX = $i_NTP_Server_Count Then $i_NTP_Server_IDX = 0

    While 1
        $sNTP_Time_Static = _NTP_GetTime_PL($aNTP_Servers[$i_NTP_Server_IDX])
        If Not @error Then ExitLoop
        $i_NTP_Server_IDX += 1
        If $i_NTP_Server_IDX = $i_NTP_Server_Count Then $i_NTP_Server_IDX = 0
    WEnd
    #EndRegion - _NTP_GetTime_PLServers() - checking internet time

    $hTimer = TimerInit()
    Return $sNTP_Time_Static
EndFunc   ;==>_NTP_GetTime_PLServers

 

Signature beginning:
Please remember: "AutoIt"..... *  Wondering who uses AutoIt and what it can be used for ? * Forum Rules *
ADO.au3 UDF * POP3.au3 UDF * XML.au3 UDF * IE on Windows 11 * How to ask ChatGPT for AutoIt Codefor other useful stuff click the following button:

Spoiler

Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind. 

My contribution (my own projects): * Debenu Quick PDF Library - UDF * Debenu PDF Viewer SDK - UDF * Acrobat Reader - ActiveX Viewer * UDF for PDFCreator v1.x.x * XZip - UDF * AppCompatFlags UDF * CrowdinAPI UDF * _WinMergeCompare2Files() * _JavaExceptionAdd() * _IsBeta() * Writing DPI Awareness App - workaround * _AutoIt_RequiredVersion() * Chilkatsoft.au3 UDF * TeamViewer.au3 UDF * JavaManagement UDF * VIES over SOAP * WinSCP UDF * GHAPI UDF - modest begining - comunication with GitHub REST APIErrorLog.au3 UDF - A logging Library * Include Dependency Tree (Tool for analyzing script relations) * Show_Macro_Values.au3 *

 

My contribution to others projects or UDF based on  others projects: * _sql.au3 UDF  * POP3.au3 UDF *  RTF Printer - UDF * XML.au3 UDF * ADO.au3 UDF SMTP Mailer UDF * Dual Monitor resolution detection * * 2GUI on Dual Monitor System * _SciLexer.au3 UDF * SciTE - Lexer for console pane

Useful links: * Forum Rules * Forum etiquette *  Forum Information and FAQs * How to post code on the forum * AutoIt Online Documentation * AutoIt Online Beta Documentation * SciTE4AutoIt3 getting started * Convert text blocks to AutoIt code * Games made in Autoit * Programming related sites * Polish AutoIt Tutorial * DllCall Code Generator * 

Wiki: Expand your knowledge - AutoIt Wiki * Collection of User Defined Functions * How to use HelpFile * Good coding practices in AutoIt * 

OpenOffice/LibreOffice/XLS Related: WriterDemo.au3 * XLS/MDB from scratch with ADOX

IE Related:  * How to use IE.au3  UDF with  AutoIt v3.3.14.x * Why isn't Autoit able to click a Javascript Dialog? * Clicking javascript button with no ID * IE document >> save as MHT file * IETab Switcher (by LarsJ ) * HTML Entities * _IEquerySelectorAll() (by uncommon) * IE in TaskSchedulerIE Embedded Control Versioning (use IE9+ and HTML5 in a GUI) * PDF Related:How to get reference to PDF object embeded in IE * IE on Windows 11

I encourage you to read: * Global Vars * Best Coding Practices * Please explain code used in Help file for several File functions * OOP-like approach in AutoIt * UDF-Spec Questions *  EXAMPLE: How To Catch ConsoleWrite() output to a file or to CMD *

I also encourage you to check awesome @trancexx code:  * Create COM objects from modules without any demand on user to register anything. * Another COM object registering stuffOnHungApp handlerAvoid "AutoIt Error" message box in unknown errors  * HTML editor

winhttp.au3 related : * https://www.autoitscript.com/forum/topic/206771-winhttpau3-download-problem-youre-speaking-plain-http-to-an-ssl-enabled-server-port/

"Homo sum; humani nil a me alienum puto" - Publius Terentius Afer
"Program are meant to be read by humans and only incidentally for computers and execute" - Donald Knuth, "The Art of Computer Programming"
:naughty:  :ranting:, be  :) and       \\//_.

Anticipating Errors :  "Any program that accepts data from a user must include code to validate that data before sending it to the data store. You cannot rely on the data store, ...., or even your programming language to notify you of problems. You must check every byte entered by your users, making sure that data is the correct type for its field and that required fields are not empty."

Signature last update: 2023-04-24

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...