Jump to content

Check if between two dates


meltingpoint

Recommended Posts

I have a flat file similar to;

 

10/20/2009|data|data|data|1500

10/21/2009|data|data|data|1000

10/28/2009|data|data|data|2000

 

I will have two form entries ($begin_date, $end_date) and wish to loop through and echo those dates that fall between $begin_date and $end_date.

 

I have searched the form and spent much time on google.  Need a point in the right direction.

 

Andy

Link to comment
https://forums.phpfreaks.com/topic/167338-check-if-between-two-dates/
Share on other sites

Dates in that format (MM/DD/YYYY) cannot be compared in less-than/greater-than tests. You must use or get your dates in a format that has the year as the MSD (Most Significant Digit) and the day as the LSD (Least Significant Digit.) If you had YYYY/MM/DD or YYYYMMDD or YYYY-MM-DD you could easily (and quickly) do less-than/greater-than comparisons using dates. As an alternate, you could convert to Unix Timestamps to do the less-than/greater-than comparison (make sure if you do it this way that you take into account the HH:MM:SS part of the timestamp so that your comparisons for dates will operate as expected.)

Well...........the project is in it's begiing stages and I can switch both the existing flat file data and the form input to reflect the YYYY/MM/DD format. 

 

If I do that, how would it be a simple comparison of

 

if ($a >= $begin_date && $a <= $end_date)

{

do something

}

I'm not sure if your last post is a question or a statement (that is how you would do the comparison) -

 

<?php
// 2009/10/20|data|data|data|1500
$file = "data.dat";
$begin_date = "2009/10/21";
$end_date = "2009/10/21";
$sep = "|";

$handle = fopen($file, "r");
$matches = array();
while (($data = fgetcsv($handle, 1000, $sep)) !== FALSE) {
// $data[0] is the date field
if($data[0] >= $begin_date && $data[0] <= $end_date){
	$matches[] = $data; // copy matching entry
}
}
fclose($handle);
echo "<pre>",print_r($matches,true),"</pre>"; // show results
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.