【问题标题】:Checking the difference between two dates检查两个日期之间的差异
【发布时间】:2014-06-12 09:48:11
【问题描述】:

我正在尝试创建一个 if 语句来比较两个时间/日期,并查看第二个日期是否在输入第一个日期后不到 24 小时。如果是,则不应允许该语句继续

$date 是在代码前面设置的,是用户输入的日期。

$now = new DateTime();
$future_date = new DateTime($date);

$interval = $future_date->diff($now);

//echo $interval->format("%d days, %h hours, %i minutes, %s seconds");

if ($interval > 60 * 60 * 24) {

这是我试图用来比较给出的日期是否相同的代码,但老实说,我真的不知道如何开始。

if ($interval > 60 * 60 * 24) {

编辑: 我真的不知道它是否真的有效,因为无论如何它都会出现一个空白页面。

  $BookID = $_GET['BookID'];
  $id = $_GET['id'];

 $query = mysqli_query($con,"SELECT time, date FROM tbl_booking WHERE BookID={$BookID} && tbl_mem_id={$id}");
$info = mysqli_fetch_assoc( $query);

$test = $info['date'] . $info['time'];

$date = date("Y-m-d H:i:s", strtotime($test));

$plus24hours = new DateTime("+1 day");
$future_date = new DateTime($date);



 if (isset($_SESSION['id']) && $_SESSION['id'] == $_GET['id']) {

 if (isset($_GET['BookID']) && is_numeric($_GET['BookID']))
 {

if ($future_date > $plus24hours) {

header("refresh:5;url=dashboard.php");
echo "Your booking has been cancelled.";   

$sql = "DELETE FROM `tbl_booking` WHERE `BookID`={$BookID}";
$result = mysqli_query($con, $sql);

 }}
 } else {
 // if id isn't set, or isn't valid, redirect back to view page
header("refresh:5;url=dashboard.php");
echo ("Sorry, there is less than 24 hours left and you cannot cancel.");


 }

【问题讨论】:

标签: php string date datetime


【解决方案1】:

这比你想象的要容易。只需将第一个日期加上 24 小时,然后将其与未来日期进行比较。如果未来日期小于第一个日期,则小于未来 24 小时。

$plus24hours = new DateTime("+1 day");
$future_date = new DateTime($date);

if ($future_date < $plus24hours) {
    // Less than 24 hours in the future
}

【讨论】:

  • 谢谢@AmalMurali。我永远不会那么/比正确。
  • 可捕获的致命错误:DateTime 类的对象无法转换为字符串
  • Works for me。你在哪一行得到这个错误?
  • 我认为这是我的代码中的另一个问题,但我不确定是什么。在主帖中发布了完整的代码。
【解决方案2】:

您可以通过将两个 DateTime 对象转换为时间戳来获得以秒为单位的差异。 $diffInSeconds = $future_date-&gt;getTimestamp() - $now-&gt;getTimestamp();

如果此操作只需要DateTime 对象,那么使用strtotime 可能会更好。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-12
    • 2015-09-14
    相关资源
    最近更新 更多