Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Is given Time between to other Times?

Status
Not open for further replies.

barnarp

Programmer
May 7, 2002
16
ZA
Hi,

I am given a start time and an end time in string format like this:

TimeStart := '2006/01/12 08:00:00'
TimeEnd := '2006/01/12 12:00:00'

I then have a time variable in the 'hh24:mm' string format like this:

TimeVar := '09:30'

I need to find out if TimeVar is between TimeStart and TimeEnd?

Can someone please assist?
 
Something like this:

Code:
var
  DateStr1 : AnsiString;
  DateStr2 : AnsiString;
  Date1    : TDateTime;
  Date2    : TDateTime;
  TimeStr  : AnsiString;
  Time     : TDateTime;
begin
  ...
  DateStr1 := '2006/01/12 08:00:00'
  DateStr2 := '2006/01/12 12:00:00'
  TimeStr := '09:30'
  ...
  {Convert the strings to TDateTime first.}
  Date1 := StrToDateTime(DateStr1);    
  Date2 := StrToDateTime(DateStr2);    
  Time  := StrToDateTime(TimeStrStr);
  {Get the times from the dates.}
  Date1 := Frac(Date1); // Time part of Date1
  Date2 := Frac(Date2); // Time part of Date2
  {Compare.}
  if (Date1 <= Time) and (Date2 >= Time)
    then ... // in between
    else ... // nope
  ...   
end;

TDateTime is a float number. The integer part is the date and the fractional part is the time. You can take any part (or the whole entity) and compare them directly.

Of course, comparing dates (only) against times (only) or the whole entity against an entity part makes no sense :); that is why you need to get the times part first.

buho (A).
 
The StrToTime function can make the coding a little simpler. It would be sensible to put a try..except construct around this code to trap any invalid dates or times.
Code:
var
  DateStr1: string;
  DateStr2: string;
  TimeStr: string;
begin
  DateStr1 := '2006/01/12 08:00:00';
  DateStr2 := '2006/01/12 12:00:00';
  TimeStr := '09:30';

  if ( StrToTime(TimeStr) < StrToTime( RightStr( DateStr1, 8 ) ) ) or
    ( StrToTime(TimeStr) > StrToTime( RightStr( DateStr2, 8 ) ) ) then
    ShowMessage('Not between')
  else
    ShowMessage('Between');
end;

Andrew
Hampshire, UK
 
Arrggggg Tower! C-like code in a PASCAL forum? :) :)

Nice to meet you again, btw.

And yes... my code is wrong; Date1 <= Time1; Date2 >= Time1 is a mistake.

buho (A).



 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top