Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would I test if date is in date range (both strings)?

I have two strings, for example 05.04.2002 and 23.01-2002 - 23.06.2002.

How would I find out if the date in my first string is between the dates in the second string?

What I have been thinking

dateString := '05.04.2002';
dateRangeString := '23.01-2002 - 23.06.2002';

date := StrToDate( dateString );
rangeStart := StrToDate( LeftStr(dateRangeString, 10) );
rangeEnd := StrToDate( RightStr(dateRangeString, 10) );

Now from there I don't know what to do!

like image 702
Joel Peltonen Avatar asked Dec 08 '22 22:12

Joel Peltonen


2 Answers

You can use the unit System.DateUtils and its function DateInRange:

var
  dStart, dEnd, d2Test: TDate;
begin
  dStart := StrToDate('25/07/2012');
  dEnd   := StrToDate('29/07/2012');

  d2Test := StrToDate('26/07/2012');

  if DateInRange(d2Test, dStart, dEnd) then
    ShowMessage('In range!');

You can also check the fourth parameter of this function (AInclusive: Boolean = True)... depending on your need...

like image 147
Whiler Avatar answered Dec 31 '22 12:12

Whiler


A TDateTime variable is essentially a double variable, and the order between two date-time values (considered as date-time values) is the same as the order between the values considered as real numbers.

procedure TForm4.FormCreate(Sender: TObject);
var
  d1, d2, d: TDate;
begin
  d1 := StrToDate('2012-07-25');
  d2 := StrToDate('2012-07-29');

  d := StrToDate('2012-07-26');

  if (d1 <= d) and (d <= d2) then
    ShowMessage('In range!');
end;

Of course, using Math, you can also write

  if InRange(d, d1, d2) then
      ShowMessage('In range!');
like image 39
Andreas Rejbrand Avatar answered Dec 31 '22 12:12

Andreas Rejbrand