DateTime

Round time to 5 seconds

Posted in DateTime

This example shows, how to round time to 5 seconds. For example, if current time is 10:12:43, then rounded time will be 10:12:45 or if current time is 10:12:57, then rounded time will be 10:12:55. For this, we should multiply our variable of DateTime type to 17280 (this is count of minutes per year), round it and divide it on 17280 (for getting variable of DateTime type again).

procedure TForm1.Button1Click(Sender: TObject);
begin
  Caption:=DateTimeToStr(Round(Now*17280)/17280);
end;

Put current time to the title

Posted in DateTime

Use Timer component and this code for onTimer event.

procedure TForm1.Timer1Timer(Sender: TObject);
begin
  Form1.Caption:=DateTimeToStr(Now);
end;

Get week number of the year

Posted in DateTime

Try this algorithm:

var
  Year, Month, Day: Word;
...
procedure TForm1.Button1Click(Sender: TObject);
var
  YourDate, JunFirst: TDateTime;
  Week, More, Days: Integer;
  DaysLeft: Real;
begin
  YourDate:=StrToDate(Edit1.Text);
  DecodeDate(YourDate, Year, Month, Day);
  JunFirst:=EncodeDate(Year, 1, 1);
  case DayOfWeek(YourDate) of
    1   : More:=0;
    2..7: More:=1;
  end;
  Days:=Trunc(YourDate-JunFirst)+1;
  Week:=(Days div 7)+More;
  DaysLeft:=Days mod 7;
  case DayOfWeek(JunFirst) of
    1   : More:=1;
    2..7: More:=9-DayOfWeek(JunFirst);
  end;
  if (DaysLeft-More>=0) then Week:=Week+1;
  Label2.Caption:='Week number '+IntToStr(Week);
end;

Get difference between of 2 dates

Posted in DateTime

You can use operation of a difference between dates. The answer is a count of days between them.

procedure TForm1.Button1Click(Sender: TObject);
begin
  Label3.Caption:=FloatToStr(
    StrToDate(Edit1.Text)-StrToDate(Edit2.Text))+
      ' days between of this dates';
end;

Get day of week using date

Posted in DateTime

You may use DayOfWeek function. DayOfWeek returns the day of the week for a specified date..

procedure TForm1.Button1Click(Sender: TObject);
var
  MyDate: TDateTime;
begin
  MyDate:=StrToDateTime(Edit1.Text);
  case DayOfWeek(MyDate) of
    1: Label2.Caption:='Sanday';
    2: Label2.Caption:='Monday';
    3: Label2.Caption:='Tuesday';
    4: Label2.Caption:='Wednesday';
    5: Label2.Caption:='Thursday';
    6: Label2.Caption:='Friday';
    7: Label2.Caption:='Saturday';
  end;
end;