如何通过PHP判断MySQL中的日期时间字段是否过去? [关闭]

问题描述:

I'm building a website for a school, with a place the teachers can add assignments. All these assignments are stored in a MySQL table, with a field of type datetime that stores the due date. I'm looking for a way, with PHP, to check if the due date is in the past so I can provide visual feedback for the teachers and students. Any help would be appreciated!

我正在为学校建立一个网站,教师可以添加作业。 所有这些分配都存储在MySQL表中,其中包含datetime类型的字段,用于存储截止日期。 我正在寻找一种方法,用PHP来检查截止日期是否已经过去,这样我就可以为老师和学生提供视觉反馈。 任何帮助将不胜感激! p> div>

I would use PHP's date comparison tools. Here is an example:

$date1 = new DateTime("now");
$date2 = $yourDateFromTheDatabase;
if ($date2 < $date1) {
    //it still has time
} else {
    //time has passed
}

Does that help? You can find more examples here: http://php.net/manual/en/datetime.diff.php

Depending on how you're storing dates into the datetime field (hopefully you're using TIMESTAMP), you can use the PHP strtotime function, which parses the MySQL timestamp into a Unix timestamp which can be used for comparing PHP values. Here's an example:

$res = mysql_query("SELECT datetime FROM assignments;");

while ( $row = mysql_fetch_array($res) ) {
    $date = date("g:i a F j, Y ", strtotime($row["date"]));
}

And do your comparisons with the $date variable. That's a super broad and rough look at an idea, but hopefully it helps somewhat.

You can read more about this concept here.

Good luck!

You could actually handle this with MYSQL in your query, which i would find easier because then you don't have to handle dates in php. For example:

SELECT DueDate, (DueDate < CURDATE()) FROM table;

(DueDate < CURDATE()) returns 0/1

otherwise:

Compare given date with today