Date range question
If I have 2 dates, 21/05/2010 and 23/05/2010, how can I find out if 22/05/2006 7:16 AM exists in between them?
I am using the following code to calculate the min/max date and will then SELECT ALL records in the table tha开发者_如何学编程t are clear to update them.
$today = date('l');
if($today == 'Wednesday'){
$min = date('d/m/Y', strtotime('0 days'));
$max = date('d/m/Y', strtotime('+6 days'));
}else if($today == 'Thursday'){
$min = date('d/m/Y', strtotime('-1 days'));
$max = date('d/m/Y', strtotime('+5 days'));
}else if($today == 'Friday'){
$min = date('d/m/Y', strtotime('-2 days'));
$max = date('d/m/Y', strtotime('+4 days'));
}else if($today == 'Saturday'){
$min = date('d/m/Y', strtotime('-3 days'));
$max = date('d/m/Y', strtotime('+3 days'));
}else if($today == 'Sunday'){
$min = date('d/m/Y', strtotime('-4 days'));
$max = date('d/m/Y', strtotime('+2 days'));
}else if($today == 'Monday'){
$min = date('d/m/Y', strtotime('-5 days'));
$max = date('d/m/Y', strtotime('+1 days'));
}else if($today == 'Tuesday'){
$min = date('d/m/Y', strtotime('-6 days'));
$max = date('d/m/Y', strtotime('0 days'));
}
DateTime::diff
Create a DateTime::diff between 21/05/2010 and 22/05/2006 7:16 AM, as well as a DateTime::diff between 23/05/2010 and 22/05/2006 7:16 AM.
Then check that the first DateTime::diff is > 0
, and the second is < 0
Update : used Datetime::createFromFormat, which is a php5.3 method
Update2 : Tested code sample. Produces expected output.
<?php
$datetime_lower = DateTime::createFromFormat('d/m/Y', '21/05/2010');
$datetime_upper = DateTime::createFromFormat('d/m/Y', '23/05/2010');
$datetime_compare = DateTime::createFromFormat('d/m/Y g:i a', '22/05/2006 7:16 AM');
var_dump($datetime_lower < $datetime_compare);
var_dump($datetime_upper > $datetime_compare);
if ($datetime_lower < $datetime_compare && $datetime_upper > $datetime_compare) {
echo " + date is between";
} else {
echo " date is not between";
}
Also, there is a procedural date_diff function
Use strtotime
$date1 = strtotime($date1);
$date2 = strtotime($date2);
$datefind = strtotime($datefind);
if ($datefind >= $date1 && $datefind <= $date2)
Explode your dates and use the parts in a mktime() to get their timestamp values. Then it's a simple matter of checking if your timestamp is larger or smaller than the others.
http://php.net/manual/en/function.mktime.php
Pseudocode:
$parts= explode("/", "21/05/2010");
$timestamp1= mktime($parts[0], $parts[1], ...);
if($timestamp1 < $timestamp2...) {
print "timestamp1 is older then timestamp2";
}
精彩评论