【问题标题】:Check if date is in 'Y-m-d' format and is not in future date?检查日期是否为“Y-m-d”格式且不在未来日期?
【发布时间】:2018-05-08 03:12:09
【问题描述】:

我有一个表单来捕获一个日期格式的帖子输入字段,我需要检查这个帖子字段是否为Y-m-d 格式并且日期不是任何未来的日期。

$dob = $_POST['dob']; 
// 1995-11-03 => Correct format
// 1995-30-12 => Incorrect format
// 2018-09-23 => Incorrect future date

【问题讨论】:

  • 你永远不能相信用户能正确输入。交换月份和日期的位置可能仍然使它看起来有效但不正确。我建议使用日历选择器来选择日期,这样你就可以控制输入
  • 日历选择器是 javascript,可以禁用,或者网络请求可能被伪造

标签: php validation date


【解决方案1】:
list($year, $month, $day) = explode('-', $_POST['dob']);
$timestamp = mktime(0, 0, 0, $month, $day, $year);

// Check if the date is valid, and that it's in the past
$isValid = checkdate($month, $day, $year) && $timestamp <= time();

手册:http://php.net/manual/en/function.checkdate.phphttp://php.net/manual/en/function.mktime.php

【讨论】:

  • 它会检查日期是否不在未来的日期吗?
  • 已更新,希望对您有所帮助
  • 我试图检查日期是否不是未来日期mktime(0, 0, 0, $month, $day, $year) &lt;= time(),但它不起作用?日期是2018-11-11
  • 它对我来说很好 - 这是一个包含一些伪单元测试的示例,向您展示:eval.in/1000762
  • 哦,对不起,我的错
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-05-25
  • 2011-02-19
  • 1970-01-01
  • 2023-03-08
  • 2014-04-27
  • 2013-02-10
  • 2010-12-23
相关资源
最近更新 更多