在示例中,我需要检查日期是否包含在日期范围内,问题我只需要比较日期和月份而不是年份。 感谢
$start_date = '2009-06-17';
$end_date = '2009-09-05';
$date_from_user = '2009-08-28';
check_in_range($start_date, $end_date, $date_from_user);
function check_in_range($start_date, $end_date, $date_from_user)
{
// Convert to timestamp
$start_ts = strtotime($start_date);
$end_ts = strtotime($end_date);
$user_ts = strtotime($date_from_user);
// Check that user date is between start & end
return (($user_ts >= $start_ts) && ($user_ts <= $end_ts));
}
答案 0 :(得分:1)
使用date()
format nd
(连接到零填充日的月份)删除年份,然后您有一个3-4位数字,您可以比较不使用日期的年份:< / p>
function check_in_range($start_date, $end_date, $date_from_user)
{
// Convert to timestamp
$start_ts = date('nd', strtotime($start_date));
$end_ts = date('nd', strtotime($end_date));
$user_ts = date('nd', strtotime($date_from_user));
// Check that user date is between start & end
return (($user_ts >= $start_ts) && ($user_ts <= $end_ts));
}
事实上,您可以传递以下格式:
function check_in_range($start_date, $end_date, $date_from_user, $comparator = 'Ymd')
{
// Convert to timestamp
$start_ts = date($comparator, strtotime($start_date));
$end_ts = date($comparator, strtotime($end_date));
$user_ts = date($comparator, strtotime($date_from_user));
// Check that user date is between start & end
return (($user_ts >= $start_ts) && ($user_ts <= $end_ts));
}
check_in_range('2017-05-30', '2017-09-12', '2015-08-06', 'nd') // true
check_in_range('2017-05-30', '2017-09-12', '2015-05-06', 'nd') // false
答案 1 :(得分:0)
您可以使用PHP DateTime类。使用代码的示例:
$start_date = '2009-06-17';
$end_date = '2009-09-05';
$x = new DateTime($start_date);
$y = new DateTime($end_date);
$dateDifference = $x->diff($y);
// see difference in days using $dateDifference->d
// see difference in months using $dateDifference->m