How to get time from internet

Just starting out? Need help? Post your questions and find answers here.
AZJIO
Addict
Addict
Posts: 2178
Joined: Sun May 14, 2017 1:48 am

How to get time from internet

Post by AZJIO »

There are 3 cases when such a program is needed.
1. The computer battery is damaged, and help can only be done remotely.
2. The motherboard spoils the battery within 3 days.
3. Boot Windows after Linux. Even if Linux can be configured, the LiveCD will still mess up the time.

There is a ready-made program, but the zone does not match in it, the difference is 1 hour.

I found this, but I need an internet request.
User avatar
ChrisR
Addict
Addict
Posts: 1466
Joined: Sun Jan 08, 2017 10:27 pm
Location: France

Re: How to get time from internet

Post by ChrisR »

You can do it using the windows time service and W32tm.exe command-line tool:
Open cmd as admin
Start the windows time service: net start w32time
Then use: w32tm /stripchart /computer:time.windows.com /dataonly /samples:5
It will give you the offset between the computer and the Internet time.

For the example, I have set the time back on my PC by 1 hour (23:30 > 22:30)

Code: Select all

C:\Windows\system32>w32tm /stripchart /computer:time.windows.com /dataonly /samples:5
Suivi de time.windows.com [51.145.123.29:123].
Collecte de 5 échantillons.
L’heure actuelle est 06/05/2022 22:30:39.
22:30:39, +3602.1800271s
22:30:41, +3602.1811302s
22:30:43, +3602.1798795s
22:30:45, +3602.1800844s
22:30:47, +3602.1802007s
22:30:47 + 3602s > Internet time = 23:30:49
BarryG
Addict
Addict
Posts: 4166
Joined: Thu Apr 18, 2019 8:17 am

Re: How to get time from internet

Post by BarryG »

This one still seems to work -> https://www.purebasic.fr/english/viewto ... 28#p352028

Just replace "ptbtime2.ptb.de" with "time.fu-berlin.de" in the code. Shows the right time and date here.
AZJIO
Addict
Addict
Posts: 2178
Joined: Sun May 14, 2017 1:48 am

Re: How to get time from internet

Post by AZJIO »

Download

Code: Select all

[set]
auto = 0
add = 5
server = time.fu-berlin.de
the command line "addhour server auto", for example "3 time.fu-berlin.de 1"

Administrator rights are required

Code: Select all

EnableExplicit

; ts-soft
; https://www.purebasic.fr/english/viewtopic.php?p=352028#p352028
; Changed input parameters in contrast to the original
Procedure GetInternetTime(Server.s, addhour)
	Protected lSocket = OpenNetworkConnection(Server, 37)
	Protected *lBuffer, lNTPTime
	
	If lSocket
		Repeat
			Select NetworkClientEvent(lSocket)
				Case #PB_NetworkEvent_Data
					*lBuffer = AllocateMemory(5)
					If *lBuffer
						If ReceiveNetworkData(lSocket, *lBuffer, 4) = 4                       
							lNTPTime = (PeekA(*lBuffer + 0)) << 24
							lNTPTime + (PeekA(*lBuffer + 1)) << 16
							lNTPTime + (PeekA(*lBuffer + 2)) << 8
							lNTPTime + (PeekA(*lBuffer + 3))
							
							lNTPTime = AddDate(lNTPTime - 2840140800, #PB_Date_Year, 20)
							lNTPTime = AddDate(lNTPTime, #PB_Date_Hour, addhour)
							
							FreeMemory(*lBuffer)
						EndIf
						CloseNetworkConnection(lSocket)
						Break
					EndIf
			EndSelect
		ForEver
	EndIf
	
	ProcedureReturn lNTPTime
EndProcedure

InitNetwork()


Define DateTime
Define Input$
Define PathConfig$
Define Count
Define ini$
Define NotINI = 1
Define auto = 0
Define addhour = 3
Define server$ = "time.fu-berlin.de"

;- ini
PathConfig$ = GetPathPart(ProgramFilename())
If FileSize(PathConfig$ + "DateTime.ini") = -1
	CompilerSelect #PB_Compiler_OS
		CompilerCase #PB_OS_Windows
			PathConfig$ = GetHomeDirectory() + "AppData\Roaming\DateTime\"
; 		CompilerCase #PB_OS_Linux
; 			PathConfig$ = GetHomeDirectory() + ".config/DateTime/"
; 		CompilerCase #PB_OS_MacOS
; 			PathConfig$ = GetHomeDirectory() + "Library/Application Support/DateTime/"
	CompilerEndSelect
EndIf
ini$ = PathConfig$ + "DateTime.ini"


If FileSize(ini$) > 5 And OpenPreferences(ini$)
	NotINI = 0
	PreferenceGroup("set")
	auto = ReadPreferenceInteger("auto", auto)
	addhour = ReadPreferenceInteger("add", addhour)
	server$ = ReadPreferenceString("server", server$)
	ClosePreferences()
EndIf


Count = CountProgramParameters()
If Count > 0
	addhour = Val(ProgramParameter(0))
	If Count > 1
		server$ = ProgramParameter(1)
		If Count > 2
			auto = Val(ProgramParameter(2))
		EndIf
	EndIf
EndIf

If NotINI And Not Count
	Input$ = InputRequester("Specify zone", "For example, for Moscow it is 3", "")
	If Asc(Input$)
	   addhour = Val(Input$)
	EndIf
EndIf

DateTime = GetInternetTime(server$, addhour)

If Not auto
	If MessageRequester("Set this time in the tray?", FormatDate("%hh:%ii:%ss %dd.%mm.%yyyy", DateTime), #PB_MessageRequester_YesNo) = #PB_MessageRequester_No
		End
	EndIf
EndIf

Define SetTime.SYSTEMTIME
With SetTime
	\wDay = Day(DateTime)
	\wMonth = Month(DateTime)
	\wYear = Year(DateTime)
	\wHour = Hour(DateTime)
	\wMinute = Minute(DateTime)
	\wSecond = Second(DateTime)
EndWith
SetLocalTime_(@SetTime)
User avatar
ChrisR
Addict
Addict
Posts: 1466
Joined: Sun Jan 08, 2017 10:27 pm
Location: France

Re: How to get time from internet

Post by ChrisR »

Works well, thanks to you and ts-soft :)
Instead of:

Code: Select all

Input$ = InputRequester("Specify zone", "For example, for Moscow it is 3", "")
You can use, if you wish:

Code: Select all

Procedure.f GetTimeZoneOffset()
  Protected nOffSet.f, iTimeZone.Time_Zone_Information
  With iTimeZone
    Select GetTimeZoneInformation_(iTimeZone)
      Case #TIME_ZONE_ID_STANDARD
        nOffSet = (\Bias+\StandardBias)
      Case #TIME_ZONE_ID_DAYLIGHT
        nOffSet = (\Bias+\DaylightBias)
      Default : nOffSet = 0
    EndSelect
  EndWith
  ProcedureReturn -nOffSet/60
EndProcedure

Debug "TimeZone UTC+ " + StrF(GetTimeZoneOffset(),0) + " Hour"
AZJIO
Addict
Addict
Posts: 2178
Joined: Sun May 14, 2017 1:48 am

Re: How to get time from internet

Post by AZJIO »

ChrisR wrote: Sat May 07, 2022 11:56 pm GetTimeZoneOffset
Returns 0, but it should be 5

Code: Select all

    Default
        nOffSet = (\Bias+\StandardBias)
this returns what was expected

A few years ago, in our country, they experimented with zones, everyone's time was spoiled. After that, I think it should be possible to set the offset manually so as not to get into an uncontrolled situation.
User avatar
Keya
Addict
Addict
Posts: 1890
Joined: Thu Jun 04, 2015 7:10 am

Re: How to get time from internet

Post by Keya »

as a programmer, I do not like Daylight Savings Time (DST) lol
Barry's link (and update by AZJIO) is a real nice simple example of using the NTP protocol though
AZJIO
Addict
Addict
Posts: 2178
Joined: Sun May 14, 2017 1:48 am

Re: How to get time from internet

Post by AZJIO »

Update
https://www.purebasic.fr/english/viewto ... 10#p584010

1. Added enumeration of servers.
2. notauto = 0 - No dialog boxes. notauto = 1 - Timezone request possible. notauto = 2 - you will be prompted to set the specified time, showing a successful server and access time (but the time is not exactly set, there will be a shift from the moment the dialog box appears until the "yes" button is pressed).
3. addhour = 2 - manual setting of the time zone. If you set >24, then the time zone is requested from the OS.
Post Reply