一尘不染

如何检查日期是否在给定范围内?

php

如果有$start_date$end_date,如何检查用户给出的日期是否在该范围内?

例如

$start_date = '2009-06-17';

$end_date = '2009-09-05';

$date_from_user = '2009-08-28';

目前日期是字符串,将它们转换为时间戳整数是否有帮助?


阅读 368

收藏
2020-05-26

共1个答案

一尘不染

使用strtotime将它们转换为时间戳是正确的方法,例如

$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));
}
2020-05-26