Capturar a data e hora do servidor

Delphi

03/10/2005

Caro colegas

Estou com uma duvida que não consigo solucioar

Duviada:

Como capturar a data e hora em uma variavel
var
WDate : TDateTime;
WHora : TDateTime;

Uso o BDE, com paradox, quero achar o alias ´Comercio´, capturar o servidor deste alias, e deste servidor, capturar, a data e hora nestas duas variaveis acima descritas ´WDate e WHora´.

Agadeço desde já pela ajuda.

Atenciosamente


M

M

Curtidas 0

Respostas

Bruno Belchior

Bruno Belchior

03/10/2005

se vc utiliza Banco de Dados, pode retornar esses valores via SQL...
select Current_Time, Current_Date from RDB$Database



GOSTEI 0
Armando.boza

Armando.boza

03/10/2005

[quote:a2c46f8584=´Bruno Belchior´]se vc utiliza Banco de Dados, pode retornar esses valores via SQL...
select Current_Time, Current_Date from RDB$Database
[/quote:a2c46f8584]

anotado


GOSTEI 0
Vinicius2k

Vinicius2k

03/10/2005

[quote:a1f54a8250=´Bruno Belchior´]se vc utiliza Banco de Dados, pode retornar esses valores via SQL...
select Current_Time, Current_Date from RDB$Database
[/quote:a1f54a8250]

Acho que a sugestão não se aplica visto que o colega utiliza paradox + BDE.
Também *creio* que não seja possível implementar isso. A não ser que se dê ´várias voltas´... Uma teoria seria: através de units da BDE descobrir o path do álias, depois verificar qual o caminho na rede para a unidade mapeada que consta no path do alias e, enfim, através alguma API trazer data e hora da máquina da rede.

T+


GOSTEI 0
Bruno Belchior

Bruno Belchior

03/10/2005

Acho que a sugestão não se aplica visto que o colega utiliza paradox + BDE.
Após postar que reparei nessa parte... :oops:


GOSTEI 0
Delphi32

Delphi32

03/10/2005

Entre as execuções do programa o servidor pode mudar?

Desde que comecei com o Firebird venho usando as funções citadas acima (CURRENT_DATE e CURRENT_TIME), mas quando ainda usava Paradox + BDE eu fiz serviço para Windows com o componente IdTimeServer da Indy. Através do componente IdTime (que é o cliente) eu acessava o servidor e retornava a data e hora nele.

Talvez isso te dê uma luz...

Até!


GOSTEI 0
Edilcimar

Edilcimar

03/10/2005

vc me enviou uma mp perguntando sobre isto, se fosse em firebird, eu sei pois existe função para retornar a hora e função para retornar a data, porém usando o piradox eu não sei, talvez outra pessoa saiba


GOSTEI 0
Emerson Nascimento

Emerson Nascimento

03/10/2005

bem, se puder ser via programa em delphi, eu posso enviar um exemplo.
vc só precisa indicar o nome do computador que será o servidor e pronto... o programa trará a data e a hora desse computador.


GOSTEI 0
Emerson Nascimento

Emerson Nascimento

03/10/2005

funciona inclusive em computadores remotos - fora da sua rede, se informar o IP


GOSTEI 0
Edilcimar

Edilcimar

03/10/2005

emerson, se puder colocar um exemplo eu também agradeço


GOSTEI 0
Emerson Nascimento

Emerson Nascimento

03/10/2005

{*******************************************************}
{                                                       }
{          Remote Time Of Day Version 1.1               }
{                                                       }
{       Copyright (c) 1999-2004 Vadim Crits             }
{                                                       }
{*******************************************************}

unit RtMain;

interface

uses
  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
  StdCtrls;

type
  TMainForm = class(TForm)
    bthBrowse: TButton; // um botão com caption ´...´ (reticências)
    edtComputerName: TEdit; // inicia vazio
    Memo: TMemo; // inicia vazio
    btnGet: TButton; // caption ´Obter´
    lblComputerName: TLabel; // caption ´Nome do Computador´
    lblResults: TLabel; // caption ´Resultados´
    procedure FormCreate(Sender: TObject);
    procedure FormDestroy(Sender: TObject);
    procedure bthBrowseClick(Sender: TObject);
    procedure btnGetClick(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

  PTimeOfDayInfo = ^TTimeOfDayInfo;
  TTimeOfDayInfo = packed record
    tod_elapsedt: DWORD;
    tod_msecs: DWORD;
    tod_hours: DWORD;
    tod_mins: DWORD;
    tod_secs: DWORD;
    tod_hunds: DWORD;
    tod_timezone: Longint;
    tod_tinterval: DWORD;
    tod_day: DWORD;
    tod_month: DWORD;
    tod_year: DWORD;
    tod_weekday: DWORD;
  end;

  NET_API_STATUS = DWORD;

function NetRemoteTOD(UncServerName: LPCWSTR; BufferPtr: PBYTE): NET_API_STATUS; stdcall;
  external ´netapi32.dll´ Name ´NetRemoteTOD´;

function NetApiBufferFree(Buffer: Pointer): NET_API_STATUS; stdcall;
  external ´netapi32.dll´ Name ´NetApiBufferFree´;

const
  INIT_KEY = ´\Software\NetUtils\Rtod\´;
  STop  = ´Top´;
  SLeft = ´Left´;

resourcestring
  SSelectComputer = ´Selecione um computador´;
  SUpTime = ´Sistema ligado à ¬u dias, ¬s horas, ¬s minutos, ¬s segundos´;
  SCurrentDate = ´A data atual é: ¬s´;
  SCurrentTime = ´A hora atual é: ¬s´;

var
  MainForm: TMainForm;

implementation

uses Registry, ShlObj, ActiveX;

{$R *.dfm}

function SelectComputer(const Caption: string; out ComputerName: string): Boolean;
var
  ItemIDList: PItemIDList;
  BrowseInfo: TBrowseInfo;
  NameBuffer: array[0..MAX_PATH] of Char;
  WindowList: Pointer;
  ShellMalloc: IMalloc;
begin
  Result := False;
  if not Failed(SHGetSpecialFolderLocation(Application.Handle, CSIDL_NETWORK, ItemIDList)) then
  try
    FillChar(BrowseInfo, SizeOf(BrowseInfo), 0);
    with BrowseInfo do
    begin
      hwndOwner := Application.Handle;
      pidlRoot := ItemIDList;
      pszDisplayName := NameBuffer;
      lpszTitle := PChar(Pointer(Caption));
      ulFlags := BIF_BROWSEFORCOMPUTER;
    end;
    WindowList := DisableTaskWindows(0);
    try
      Result := Assigned(SHBrowseForFolder(BrowseInfo));
    finally
      EnableTaskWindows(WindowList);
    end;
    if Result then
      ComputerName := NameBuffer;
  finally
    if Succeeded(SHGetMalloc(ShellMalloc)) then
      ShellMalloc.Free(ItemIDList);
  end;
end;

procedure TMainForm.FormCreate(Sender: TObject);
var
  ComputerName: array[0..MAX_COMPUTERNAME_LENGTH] of Char;
  MaxComputerName: Cardinal;
begin
  with TRegistry.Create do
  try
    if OpenKey(INIT_KEY, False) then
    try
      if ValueExists(STop) then
        Top := ReadInteger(STop);
      if ValueExists(SLeft) then
        Left := ReadInteger(SLeft);
    finally
      CloseKey;
    end;
  finally
    Free;
  end;
  MaxComputerName := SizeOf(ComputerName);
  GetComputerName(ComputerName, MaxComputerName);
  edtComputerName.Text := ´\\´ + ComputerName;
end;

procedure TMainForm.FormDestroy(Sender: TObject);
begin
  with TRegistry.Create do
  try
    if OpenKey(INIT_KEY, True) then
    try
      WriteInteger(STop, Top);
      WriteInteger(SLeft, Left);
    finally
      CloseKey;
    end;
  finally
    Free;
  end;
end;

procedure TMainForm.bthBrowseClick(Sender: TObject);
var
  ComputerName: string;
begin
  SelectComputer(SSelectComputer, ComputerName);
  if ComputerName <> ´´ then
    edtComputerName.Text := ´\\´ + ComputerName;
end;

procedure TMainForm.btnGetClick(Sender: TObject);
const
  NERR_Success = 0;
var
  TimeOfDayInfo: PTimeOfDayInfo;
  ServerName: array[0..255] of WideChar;
  dwRetValue, dwDays, dwSecs: DWORD;
  GMTTime: TSystemTime;
  CurTime, UpTime: TDateTime;
  ts: TTimeStamp;
begin
  StringToWideChar(edtComputerName.Text, @ServerName, SizeOf(ServerName));
  dwRetValue := NetRemoteTOD(@ServerName, PBYTE(@TimeOfDayInfo));
  if dwRetValue <> NERR_Success then
    raise Exception.Create(SysErrorMessage(dwRetValue));
  with TimeOfDayInfo^ do
  begin
    FillChar(GMTTime, SizeOf(GMTTime), 0);
    with GMTTime do
    begin
      wYear := tod_year;
      wMonth := tod_month;
      wDayOfWeek := tod_weekday;
      wDay := tod_day;
      wHour := tod_hours;
      wMinute := tod_mins;
      wSecond := tod_secs;
      wMilliseconds := tod_hunds;
    end;
    CurTime := SystemTimeToDateTime(GMTTime);
    if tod_timezone <> -1 then
      CurTime := CurTime + ((1 / 24 / 60) * -tod_timezone);
    dwDays := 0;
    dwSecs := tod_msecs div 1000;
    if dwSecs >= SecsPerDay then
    begin
      dwDays := dwSecs div SecsPerDay;
      dwSecs := dwSecs mod SecsPerDay;
    end;
    ts.Time := dwSecs * 1000;
    ts.Date := DateDelta;
    UpTime := TimeStampToDateTime(ts);
    with Memo.Lines do
    begin
      Add(StringOfChar(´ ´, 40) + ´*** ´ + edtComputerName.Text + ´ ***´);
      Add(Format(SUpTime, [dwDays, FormatDateTime(´h´, UpTime),
                           FormatDateTime(´n´, UpTime),
                           FormatDateTime(´s´, UpTime)]));
      Add(Format(SCurrentDate, [FormatDateTime(ShortDateFormat, CurTime)]));
      Add(Format(SCurrentTime, [FormatDateTime(LongTimeFormat, CurTime)]));
      EndUpdate;
    end;
  end;
  NetApiBufferFree(TimeOfDayInfo);
end;

end.


Essa é mais ou menos a cara dele (conforme o exemplo citado acima):
+--------------------------------------------------------------+
| Remote Time Of Day                                           |
+--------------------------------------------------------------+
|                                                              |
|                    +---------------------+ +-----+ +-------+ |
| Nome do Computador |                     | | ... | | Obter | |
|                    +---------------------+ +-----+ +-------+ |
|                                                              |
| Resultados                                                   |
| +----------------------------------------------------------+ |
| |                                                          | |
| |                                                          | |
| |                                                          | |
| |                                                          | |
| |                                                          | |
| |                                                          | |
| |                                                          | |
| |                                                          | |
| |                                                          | |
| |                                                          | |
| |                                                          | |
| |                                                          | |
| |                                                          | |
| +----------------------------------------------------------+ |
+--------------------------------------------------------------+


no campo Nome do Computador pode ser digitado um IP interno, externo, um nome de Host... ou pode ser selecionado a partir do botão ´reticências´.


GOSTEI 0
Edilcimar

Edilcimar

03/10/2005

valeu, mas isto realmente é um verdadeiro jornal só para pegar a hora!


GOSTEI 0
POSTAR