Description
In this example I will write a function called Get_CurrentDateLocalTime(), that returns a TDateTime object which
contains both the current date and the local time.
The current date is easy to obtained via the Date() VCL function.
The time is calculated with the GetLocalTime() Win32 API function.
Then the VCL EncodeTime() function is used to convert the time from
the SYSTEMTIME format to TDateTime format.
From the returned object (dt) we can display both the current date and the local time on two labels owned by Form1
Form1 also contains a TButton.
Code
LocalDateTime.cpp
#include <vcl.h>
#pragma hdrstop
#include "LocalDateTime.h"
//-----------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
//-----------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
: TForm(Owner)
{
Color = 0x987facd;
}
//-----------------------------------------------------------------------
TDateTime Get_CurrentDateLocalTime()
{
// Description: Get Current Date and Local Time
SYSTEMTIME LocalTime; // SYSTEMTIME is a Windows Structure
GetLocalTime(&LocalTime); // Win32 API
return Date() + EncodeTime(LocalTime.wHour,
LocalTime.wMinute,
LocalTime.wSecond, 0);
}
//----------------------------------------------------------------------
void __fastcall TForm1::Button2Click(TObject *Sender)
{
TDateTime dt;
dt = Get_CurrentDateLocalTime();
// Display Time and Date on Labels
Label1->Caption = TimeToStr(dt);
Label2->Caption = DateToStr(dt);
}
//-----------------------------------------------------------------------
LocalDateTime.h
#ifndef LocalDateTimeH
#define LocalDateTimeH
#include <Classes.hpp>
#include <Controls.hpp>
#include <StdCtrls.hpp>
#include <Forms.hpp>
class TForm1 : public TForm
{
__published: // IDE-managed Components
TLabel *Label1;
TLabel *Label2;
TButton *Button2;
void __fastcall Button2Click(TObject *Sender);
private: // User declarations
public: // User declarations
__fastcall TForm1(TComponent* Owner);
};
//-----------------------------------------------------------------------
extern PACKAGE TForm1 *Form1;
//-----------------------------------------------------------------------
#endif
Copyright © 1997-2002 Rodolfo A. Frino. All rights reserved.