![]() |
![]() |
| Paypal | FTP | CCD | Buscar | Trucos | Trabajo | Foros |
|
|||||||
| Registrarse | FAQ | Miembros | Calendario | Guía de estilo | Temas de Hoy |
![]() |
|
|
Herramientas | Buscar en Tema | Desplegado |
|
|
|
#1
|
||||
|
||||
|
Cita:
__________________
Uno se alegra de ser útil. (Isaac Asimov) |
|
#2
|
|||
|
|||
|
Cita:
|
|
#3
|
||||
|
||||
|
Cita:
Código:
/// <summary>
/// Devuelve la hora actual formateada con uso horario.
/// </summary>
/// <returns>Hora actual formateada.</returns>
public static string leeFechaHoraInternet()
{
string retorno = DateTime.Now.ToString("yyyy-MM-dd'T'HH:mm:ssK");
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
try
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("https://www2.roa.es/cgi-bin/horautc");//https://worldtimeapi.org/api/ip");
webRequest.Method = "GET";
HttpWebResponse respuesta = (HttpWebResponse) webRequest.GetResponse();
if(respuesta.StatusCode == HttpStatusCode.OK)
{
Stream strmRespuesta = respuesta.GetResponseStream();
StreamReader leeRespuesta = new StreamReader(strmRespuesta);
string jsonRespuesta = leeRespuesta.ReadToEnd();
long ticks = long.Parse(jsonRespuesta.Replace("\\n", ""));
var fechora = Org.BouncyCastle.Utilities.Date.DateTimeUtilities.UnixMsToDateTime(ticks).ToLocalTime();//esta la uso yo porque tengo bouncy instalado
//desde el paquete nuget BouncyCastle
retorno = fechora.ToString("yyyy-MM-dd'T'HH:mm:ssK");
}
}
catch(Exception Exc)
{
retorno = DateTime.Now.ToString("yyyy-MM-dd'T'HH:mm:ssK");
}
return retorno;
}
Puede preguntar a @novatico Cita:
__________________
Uno se alegra de ser útil. (Isaac Asimov) |
|
#4
|
|||
|
|||
|
Aqua lo tenéis convertido a Delphi 10 y probado. Espero que os sirva
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. Última edición por Neftali [Germán.Estévez] fecha: 09-12-2024 a las 09:14:35. Razón: corregir TAGs del código |
|
#5
|
|||
|
|||
|
Y esto seria para delphi 7:
Código:
unit Unit2;
interface
uses
Windows, SysUtils, IdHTTP, IdSSLOpenSSL, DateUtils;
function LeeFechaHoraInternet: string;
implementation
function GetTimeZoneOffset: TDateTime;
var
TZInfo: TTimeZoneInformation;
Bias: Integer;
begin
case GetTimeZoneInformation(TZInfo) of
TIME_ZONE_ID_STANDARD, TIME_ZONE_ID_DAYLIGHT:
Bias := TZInfo.Bias + TZInfo.DaylightBias; // Ajuste según horario de verano
else
Bias := 0; // Si no se puede determinar la zona horaria, se asume UTC
end;
Result := Bias / MinsPerDay; // Convertir minutos a días
end;
function LeeFechaHoraInternet: string;
var
Http: TIdHTTP;
SSLHandler: TIdSSLIOHandlerSocketOpenSSL;
Respuesta: string;
UnixTicks: Int64;
FechaHoraUTC, FechaHoraLocal: TDateTime;
TimeZoneOffset: TDateTime;
begin
Result := FormatDateTime('yyyy-mm-dd"T"hh:nn:ss"Z"', Now); // Valor predeterminado
Http := TIdHTTP.Create(nil);
SSLHandler := TIdSSLIOHandlerSocketOpenSSL.Create(nil);
SSLHandler.SSLOptions.Method := sslvTLSv1_2;
try
Http.IOHandler := SSLHandler;
Http.Request.Accept := 'application/json';
Http.Request.UserAgent := 'Mozilla/5.0 (compatible; Delphi)';
try
// Realizar la solicitud HTTP
// Respuesta := Http.Get('https://www2.roa.es/cgi-bin/horautc');
Respuesta := Http.Get('https://www.google.com');
// Convertir la respuesta (ticks Unix) a DateTime
UnixTicks := StrToInt64(Trim(Respuesta));
FechaHoraUTC := UnixDateDelta + (UnixTicks div SecsPerDay) + (UnixTicks mod SecsPerDay) / SecsPerDay;
// Obtener el desfase horario
TimeZoneOffset := GetTimeZoneOffset;
FechaHoraLocal := FechaHoraUTC - TimeZoneOffset;
// Devolver la fecha y hora en formato ISO 8601
Result := FormatDateTime('yyyy-mm-dd"T"hh:nn:ss"Z"', FechaHoraLocal);
except
on E: Exception do
// En caso de error, devolver la hora actual
// result := E.Message;
Result := FormatDateTime('yyyy-mm-dd"T"hh:nn:ss"Z"', Now);
end;
finally
Http.Free;
SSLHandler.Free;
end;
end;
end.
|
|
#6
|
|||
|
|||
|
Hola.
He intentado usar la función pero me sale este error. ¿Sabéis como poder solucionarlo? Error connecting with SSL. error 1409442E:SSL routines:SSL3_READ_BYTES: tlsv 1 alert protocol version Gracias!!!! |
|
#7
|
|||
|
|||
|
prueba con este: A mi me funciona correctamente en delphi 7
Código:
unit Unit2;
interface
uses
Windows, SysUtils, IdHTTP, IdSSLOpenSSL, DateUtils;
function LeeFechaHoraInternet: string;
implementation
function GetTimeZoneOffset: TDateTime;
var
TZInfo: TTimeZoneInformation;
Bias: Integer;
begin
case GetTimeZoneInformation(TZInfo) of
TIME_ZONE_ID_STANDARD, TIME_ZONE_ID_DAYLIGHT:
Bias := TZInfo.Bias + TZInfo.DaylightBias; // Ajuste según horario de verano
else
Bias := 0; // Si no se puede determinar la zona horaria, se asume UTC
end;
Result := Bias / MinsPerDay; // Convertir minutos a días
end;
function LeeFechaHoraInternet: string;
var
Http: TIdHTTP;
SSLHandler: TIdSSLIOHandlerSocketOpenSSL;
Respuesta: string;
UnixTicks: Int64;
FechaHoraUTC, FechaHoraLocal: TDateTime;
TimeZoneOffset: TDateTime;
begin
Result := FormatDateTime('yyyy-mm-dd"T"hh:nn:ss"Z"', Now); // Valor predeterminado
Http := TIdHTTP.Create(nil);
SSLHandler := TIdSSLIOHandlerSocketOpenSSL.Create(nil);
try
SSLHandler.SSLOptions.Method := sslvTLSv1_2; // Usar TLS 1.2
SSLHandler.SSLOptions.SSLVersions := [sslvTLSv1_2];
SSLHandler.SSLOptions.Mode := sslmClient; // Modo cliente
// Configurar cliente con este manejador SSL
// IdHTTP1.IOHandler := SSLHandler;
// IdHTTP1.Request.UserAgent := 'Mozilla/5.0';
// Realiza la conexión HTTP/HTTPS
// IdHTTP1.Get('https://yourserver.com');
Http.IOHandler := SSLHandler;
Http.Request.Accept := 'application/json';
Http.Request.UserAgent := 'Mozilla/5.0 (compatible; Delphi)';
try
// Realizar la solicitud HTTP
Respuesta := Http.Get('https://www2.roa.es/cgi-bin/horautc');
// Respuesta := Http.Get('https://www.google.com');
// Convertir la respuesta (ticks Unix) a DateTime
UnixTicks := StrToInt64(Trim(Respuesta));
FechaHoraUTC := UnixDateDelta + (UnixTicks div SecsPerDay) + (UnixTicks mod SecsPerDay) / SecsPerDay;
// Obtener el desfase horario
TimeZoneOffset := GetTimeZoneOffset;
FechaHoraLocal := FechaHoraUTC - TimeZoneOffset;
// Devolver la fecha y hora en formato ISO 8601
Result := FormatDateTime('yyyy-mm-dd"T"hh:nn:ss"Z"', FechaHoraLocal);
except
on E: Exception do
// En caso de error, devolver la hora actual
result := E.Message;
// Result := FormatDateTime('yyyy-mm-dd"T"hh:nn:ss"Z"', Now);
end;
finally
Http.Free;
SSLHandler.Free;
end;
end;
end.
|
|
#8
|
|||
|
|||
|
Cita:
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. |
|
#9
|
||||
|
||||
|
Cita:
__________________
Uno se alegra de ser útil. (Isaac Asimov) |
|
#10
|
|||
|
|||
|
Cita:
|
|
#11
|
||||
|
||||
|
Cita:
![]() Pero si, se puede usar. |
|
#12
|
|||
|
|||
|
Me refería a los enlaces dentro de esa URL hombre!
|
![]() |
|
|
Temas Similares
|
||||
| Tema | Autor | Foro | Respuestas | Último mensaje |
| TimeStamp | Willo | MySQL | 4 | 22-03-2016 21:15:00 |
| Consulta TimeStamp | Jose Roman | SQL | 2 | 06-09-2012 04:03:11 |
| TimeStamp = TimeStamp me da error | Chogo | Firebird e Interbase | 7 | 16-03-2011 04:13:38 |
| TIMESTAMP en restriccion | Cañones | SQL | 6 | 28-08-2007 23:19:27 |
| Timestamp y bde 5.2 | Toni | Firebird e Interbase | 2 | 27-05-2003 09:26:33 |
|