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 wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Check if given date/time lies within a certain range of dates/times

Status
Not open for further replies.

Extension

Programmer
Nov 3, 2004
311
CA
I want to check if a given date/time lies within a certain range of dates/times.

I'm currently using the Date Pcalc module to check if a specific date is within the range.
But I'm having issues while building the logic to compare the times.

The date comparison is fine. See the last if statement; this is where I'm having some trouble. You'll see the logic is wrong.

Code:
# Date 1 & 2
$Date1 = "2007-06-07";
$Date2 = "2007-06-08";

# Time 1 & 2 (24-Hour Clock Format)
$Time1 = "8:30";
$Time2 = "10:30";

# Current Date
$CurrentDate = "2007-06-08";

# Current Time
$CurrentTime: "9:16";

# Convert Date Strings to Arrays
my @ArrayDate1 = split(/\-/,$Date1);
my @ArrayDate2 = split(/\-/,$Date2);
my @ArrayDateCurrent = split(/\-/,$CurrentDate);

# Convert Dates to Days
my $Days_to_Date1 = Date_to_Days(@ArrayDate1);
my $Days_to_Date2 = Date_to_Days(@ArrayDate2);
my $Days_to_DateCurrent = Date_to_Days(@ArrayDateCurrent);


# Check if Current Date Lies between Date 1 and Date 2
if (($Days_to_DateCurrent >= $Days_to_Date1) && ($Days_to_DateCurrent <= $Days_to_Date2)) {
	
	# PROBLEM IS HERE; Logic is wrong
	# If Date1 or Date2 is TODAY; check Time
	if (($Days_to_DateCurrent == $Days_to_Date1 && $CurrentTime ge $Time1) || ($Days_to_DateCurrent == $Days_to_Date2 && $CurrentTime le $Time2)) {
		
		print "Yes";
		
	}
	
}
 
Maybe $CurrentTime: "9:16";
should be $CurrentTime = "9:16";
 
If the datetimes are in this format "YYYY-MM-DD HH:MM" then you can just do a simple string comparison (assuming HH is 24 hour clock and left padded with 0's). For example:

Code:
[url=http://perldoc.perl.org/functions/my.html][black][b]my[/b][/black][/url] [blue]$lower[/blue] = [red]"[/red][purple]2007-06-07 08:30[/purple][red]"[/red][red];[/red]
[black][b]my[/b][/black] [blue]$upper[/blue] = [red]"[/red][purple]2007-06-08 10:30[/purple][red]"[/red][red];[/red]

[black][b]my[/b][/black] [blue]$current[/blue] = [red]"[/red][purple]2007-06-08 09:16[/purple][red]"[/red][red];[/red]

[olive][b]if[/b][/olive] [red]([/red][blue]$lower[/blue] le [blue]$current[/blue] and [blue]$current[/blue] le [blue]$upper[/blue][red])[/red] [red]{[/red]
	[url=http://perldoc.perl.org/functions/print.html][black][b]print[/b][/black][/url] [red]"[/red][purple]Yes[/purple][red]"[/red][red];[/red]
[red]}[/red]

Just read this page for more information on relational operators:


- Miller
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top