Page 1 of 1

how to get date and time from internet

Posted: Wed Apr 03, 2024 8:39 am
by fouednoomen
Hello all Friends ,

Hello, I need to know how I can get the date and time from the internet

Best regads
Foued Noomen

Re: how to get date and time from internet

Posted: Wed Apr 03, 2024 9:38 am
by gfilatov
fouednoomen wrote: Wed Apr 03, 2024 8:39 am Hello, I need to know how I can get the date and time from the internet
Hello Foued,

Thanks for your request :!:

It is possible with the following source code:

Code: Select all

#include "minigui.ch"

function Main()

   MsgInfo( Now() )

return nil

#pragma BEGINDUMP

#ifdef _CRT_SECURE_NO_WARNINGS
#undef _CRT_SECURE_NO_WARNINGS
#endif
#define _CRT_SECURE_NO_WARNINGS 1

#include <hbapi.h>

#ifdef __BORLANDC__
   #define _WIN32_WINNT 0x0502
#endif

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#ifdef __BORLANDC__
   #include <winsock2.h>
#endif

#include <ws2tcpip.h>

HB_FUNC( NOW )
{
    struct addrinfo hints;
    struct addrinfo *result;
    int sockfd;
    int rv;
    char buf[ 64 ];
    time_t now = time(NULL);
    char str[ 26 ];
    WSADATA wsaData;  

    WSAStartup(MAKEWORD(2,2), &wsaData);

    memset(&hints, 0, sizeof(struct addrinfo));
    hints.ai_family = AF_INET; /* Allow IPv4 */
    hints.ai_socktype = SOCK_STREAM; /* Stream socket */
    hints.ai_flags = AI_CANONNAME; /* Return canonical name */
   
    rv = getaddrinfo("www.google.com", "http", &hints, &result);
    if (rv != 0) {
        fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
        exit(1);
    }
   
    /* Create socket */
    sockfd = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
    if (sockfd == -1) {
        perror("socket");
        exit(1);
    }
   
    /* Connect */
    if (connect(sockfd, result->ai_addr, result->ai_addrlen) == -1) {
        perror("connect");
        exit(1);
    }
   
    /* Get time */
    snprintf(buf, sizeof(buf), "GET / HTTP/1.0\r\n\r\n");
    send(sockfd, buf, strlen(buf), 0);
    recv(sockfd, buf, sizeof(buf), 0);
    ctime_s( str, 26, &now );
    snprintf(buf, sizeof( buf ), "Current time: %s", str );
   
    closesocket(sockfd);
    freeaddrinfo(result);
   
    hb_retc( buf );
}

#pragma ENDDUMP
You can see the result in the picture below:
image.png
image.png (5.11 KiB) Viewed 10907 times
Hope this is helpful 8-)

Re: how to get date and time from internet

Posted: Wed Apr 03, 2024 5:00 pm
by ASESORMIX
i believed that there is a mistake.
if i change date and time of my pc,
this rutine shows the date and time of mi pc.

Re: how to get date and time from internet

Posted: Wed Apr 03, 2024 6:36 pm
by edk
NTP demo.

In the aServersNTP variable, define the addresses of the NTP servers from which you want to get the time. To get the shortest latency times possible, it is best to use local servers.

Code: Select all

/* Copyright 2013-2014 Viktor Szakats (vszakats.net/harbour) */
#include "hmg.ch"
#include "hbsocket.ch"
#include "hbver.ch"

PROCEDURE MAIN

   Set( _SET_DATEFORMAT, "yyyy.mm.dd" )

	DEFINE WINDOW Win_1 ;
		AT 0,0 ;
		WIDTH 400 ;
		HEIGHT 400 ;
		TITLE 'NTP DEMO' ;
		MAIN 

	@ 70,70 BUTTON Button_1 CAPTION 'NTP Network Time Protocol' ACTION GetTime() WIDTH 250

	END WINDOW

	CENTER WINDOW Win_1 

	ACTIVATE WINDOW Win_1 

Return

Function GetTime ()

   LOCAL tTime, i := 0, tSystemTime, tLocalTime, tOffset, cNewTime
   LOCAL aServersNTP := { "0.africa.pool.ntp.org", "0.pl.pool.ntp.org" ,"1.pl.pool.ntp.org" ,"2.pl.pool.ntp.org" ,"3.pl.pool.ntp.org" , "tempus1.gum.gov.pl", "tempus2.gum.gov.pl", "ntp.task.gda.pl", "0.europe.pool.ntp.org" }

   DO WHILE i < Len( aServersNTP )
	i ++
        WAIT WINDOW "Connecting with " + aServersNTP [i] + ".... " NOWAIT
   	tTime := hb_ntp_GetTimeUTC( aServersNTP [i], /* port 123 */ , 3000 /* 3 sec */ ) 
	tSystemTime := hb_DateTime()
	tLocalTime := tTime + hb_UTCOffset() / 86400
	IF !EMPTY(tTime)
		EXIT
	ENDIF
        WAIT WINDOW "Connecting with " + aServersNTP [i] + " no response!" NOWAIT
   ENDDO

   WAIT CLEAR 

   IF EMPTY(tTime)
	MsgStop ( "Network not available. Check Fire-Wall" )
	RETURN
   ENDIF

   tOffset := tSystemTime - tLocalTime

   MsgInfo ( "UTC    time: " + hb_valToStr ( tTime ) + " by " + aServersNTP [i] + CRLF + ;
             "Local  time: " + hb_valToStr ( tLocalTime ) + CRLF + ;
             "System time: " + hb_valToStr ( tSystemTime ) + CRLF + ;
             "Offset time: " + RoznicaCzasu ( tOffset ) )

RETURN

Function RoznicaCzasu ( tDiff )
Local tRoznica := ABS ( tDiff )
Local cGodzin := Alltrim( Str (INT( hb_NToHour (tRoznica) ), 0, 0) )
Local cMinut  := StrZero (INT( hb_NToMin (tRoznica) ) % 60, 2, 0)
Local cSekund := StrZero (INT( hb_NToSec (tRoznica) ) % 60, 2, 0)
Local cMSek   := StrZero (( hb_NToMSec (tRoznica) ) % 1000, 3, 0)
RETURN IF( tDiff < 0, "-", "" ) + cGodzin + ":" + cMinut + ":" + cSekund + "." +cMsek


/*
 * NTP functions
 *
 * Copyright 2013 Viktor Szakats (vszakats.net/harbour)
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2, or (at your option)
 * any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; see the file LICENSE.txt.  If not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301 USA (or visit https://www.gnu.org/licenses/).
 *
 * As a special exception, the Harbour Project gives permission for
 * additional uses of the text contained in its release of Harbour.
 *
 * The exception is that, if you link the Harbour libraries with other
 * files to produce an executable, this does not by itself cause the
 * resulting executable to be covered by the GNU General Public License.
 * Your use of that executable is in no way restricted on account of
 * linking the Harbour library code into it.
 *
 * This exception does not however invalidate any other reasons why
 * the executable file might be covered by the GNU General Public License.
 *
 * This exception applies only to the code released by the Harbour
 * Project under the name Harbour.  If you copy code from other
 * Harbour Project or Free Software Foundation releases into a copy of
 * Harbour, as the General Public License permits, the exception does
 * not apply to the code that you add in this way.  To avoid misleading
 * anyone as to the status of such modified files, you must delete
 * this exception notice from them.
 *
 * If you write modifications of your own for Harbour, it is your choice
 * whether to permit this exception to apply to your modifications.
 * If you do not wish that, delete this exception notice.
 *
 */


FUNCTION hb_ntp_GetTimeUTC( cServer, nPort, nTimeOut )

   LOCAL tTime := hb_SToT( "" )
   LOCAL hSocket, cBuffer

   IF HB_ISSTRING( cServer ) .AND. ! cServer == "" .AND. ;
      ! Empty( hSocket := hb_socketOpen( , HB_SOCKET_PT_DGRAM ) )
      cBuffer := hb_BChar( 8 ) + Replicate( hb_BChar( 0 ), 47 )
      IF hb_socketSendTo( hSocket, cBuffer,,, { HB_SOCKET_AF_INET, hb_socketResolveAddr( cServer ), hb_defaultValue( nPort, 123 ) } ) == hb_BLen( cBuffer )
         cBuffer := Space( 12 * 4 )
         IF hb_socketRecvFrom( hSocket, @cBuffer,,,, hb_defaultValue( nTimeOut, 10000 /* 10s */ ) ) == hb_BLen( cBuffer )
            tTime := hb_SToT( "19000101" ) + ;
               Bin2U( ntohl( hb_BSubStr( cBuffer, 10 * 4 + 1, 4 ) ) ) / 86400 + ;
               ( Bin2U( ntohl( hb_BSubStr( cBuffer, 11 * 4 + 1, 4 ) ) ) / ( 2 ^ 32 ) ) / 86400
         ENDIF
      ENDIF
      hb_socketClose( hSocket )
   ENDIF

   RETURN tTime

STATIC FUNCTION ntohl( c )

   IF hb_Version( HB_VERSION_ENDIANNESS ) == HB_VERSION_ENDIAN_LITTLE
      RETURN ;
         hb_BSubStr( c, 4, 1 ) + ;
         hb_BSubStr( c, 3, 1 ) + ;
         hb_BSubStr( c, 2, 1 ) + ;
         hb_BSubStr( c, 1, 1 )
   ENDIF

   RETURN c

STATIC FUNCTION Bin2U( c )

   LOCAL l := Bin2L( c )

   RETURN iif( l < 0, l + ( 2 ^ 32 ), l ) 
   

Re: how to get date and time from internet

Posted: Thu Apr 04, 2024 6:45 am
by serge_girard
Thanks Edward, interesting! This is all new to me.

Re: how to get date and time from internet

Posted: Fri Apr 05, 2024 10:23 am
by RPC
edk wrote: Wed Apr 03, 2024 6:36 pm NTP demo.

In the aServersNTP variable, define the addresses of the NTP servers from which you want to get the time. To get the shortest latency times possible, it is best to use local servers.
...

Thanks Edward.

Re: how to get date and time from internet

Posted: Fri Apr 05, 2024 11:07 am
by fouednoomen
Many Thanks Edward ,

Re: how to get date and time from internet

Posted: Sat Apr 06, 2024 3:24 pm
by Red2
Thank you for your informative post.

Re: how to get date and time from internet

Posted: Wed Apr 10, 2024 3:49 pm
by franco
Thanks Edward.

Re: how to get date and time from internet

Posted: Thu Apr 11, 2024 7:04 pm
by ASESORMIX
Gracias