Ver Mensaje Individual
  #7  
Antiguo 10-12-2024
razorxxx razorxxx is offline
Miembro
 
Registrado: jul 2015
Posts: 198
Reputación: 11
razorxxx Va por buen camino
Cita:
Empezado por mqm Ver Mensaje
Aqua lo tenéis convertido a Delphi 10 y probado. Espero que os sirva


Código Delphi [-]
unit Unit2;

interface

uses
  System.SysUtils, System.DateUtils, IdHTTP, IdSSLOpenSSL, System.JSON;

function LeeFechaHoraInternet: string;

implementation

function LeeFechaHoraInternet: string;
var
  Http: TIdHTTP;
  SSLHandler: TIdSSLIOHandlerSocketOpenSSL;
  Respuesta: string;
  JsonRespuesta: TJSONObject;
  UnixTicks: Int64;
  FechaHora: TDateTime;
begin
  Result := FormatDateTime('yyyy-mm-dd"T"hh:nn:ss"Z"', Now); // Formato inicial por defecto
  Http := TIdHTTP.Create(nil);
  SSLHandler := TIdSSLIOHandlerSocketOpenSSL.Create(nil);
  try
    Http.IOHandler := SSLHandler;
    Http.Request.Accept := 'application/json';
    Http.Request.UserAgent := 'Mozilla/5.0 (compatible; Delphi)';
    try
      // Realiza la solicitud a la API
      Respuesta := Http.Get('https://www2.roa.es/cgi-bin/horautc');

      // Si la respuesta es un número de ticks Unix, conviértelo
      UnixTicks := StrToInt64(Trim(Respuesta)); // Ajusta el formato si la API devuelve algo diferente
      FechaHora := UnixToDateTime(UnixTicks div 1000); // Divide entre 1000 para convertir milisegundos a segundos
      FechaHora := TTimeZone.Local.ToLocalTime(FechaHora);
      Result := FormatDateTime('yyyy-mm-dd"T"hh:nn:ss"Z"', FechaHora);
    except
      on E: Exception do
        // En caso de error, retorna la hora local
        Result := FormatDateTime('yyyy-mm-dd"T"hh:nn:ss"Z"', Now);
    end;
  finally
    Http.Free;
    SSLHandler.Free;
  end;
end;
end.


Librerías utilizadas:

IdHTTP y IdSSLOpenSSL para manejar la conexión HTTPS.
System.DateUtils para trabajar con fechas y convertir ticks Unix a TDateTime.
Formato de la fecha: Utiliza FormatDateTime para formatear las fechas en el formato ISO 8601 con zona horaria.

Manejo de errores: Si ocurre un error durante la solicitud HTTP, devuelve la hora local en el formato esperado.

Conversión de ticks Unix: La API devuelve ticks Unix en milisegundos. Esto se divide entre 1000 para convertirlos a segundos antes de usar UnixToDateTime.

Dependencia de OpenSSL: Asegúrate de que tu entorno tenga acceso a las DLL de OpenSSL (libeay32.dll y ssleay32.dll o sus equivalentes actuales) para que TIdSSLIOHandlerSocketOpenSSL funcione correctamente.
Hola a todos. ¿Realmente se puede usar https://www2.roa.es/cgi-bin/horautc, o hay que usar alguna URL propia de la AEAT?
Cuando pregunté al mail de Veri*Factu me remitieron a la siguiente web: https://sede.agenciatributaria.gob.e...a_oficial.html, pero no me he puesto a leerla a fondo.
Responder Con Cita