开发者

Comparing two date / times to find out if 5 mins has lapsed between the two times php

I need to compare two dates to show an edit link if it is within 5 mins after the post was made, in PHP. If more than 5 minutes have passed, don't show anything.

$answer_post_date = get_the_time("Y-m-d");

$current_date = date("Y-m-d");

$formated_current_date = strtotime($answer_post_date);
$formated_answer_post_date = strtotime($current_date);

At this point I have two values:

1274414400 ($formated开发者_开发问答_current_date)
1276056000 ($formated_answer_post_date)

I am not sure what to do next to check if the current date/time is > 5 mins from the answer post date.

Any suggestions would be great.

All I really need the answer to be is a Boolean (yes/no) and if yes, display the minuets left to show the link to edit.


You're only handling dates, how are you supposed to know if the difference is 5 minutes?

Anyway, I'd say the majority of the PHP code that uses the default PHP functions is at least somewhat broken. The problem is you, despite a unix timestamp storing the correct point in time something happens, it does not store timezone information. See here.

So, forget using only date and strtotime. Use the datetime extension.

Store in the database the Unix timestamp and the timezone (by timezone I mean e.g. Europe/Lisbon). Then:

$tz = new DateTimeZone($timezone);
$answer_post_date = new DateTime("$timestamp");
$answer_post_date->setTimeZone($tz);
$current_date = new DateTime("now", $tz);

$diff = $current_date->diff($answer_post_date);
if ($diff->format("a") > 0 ||
        $diff->format("h") > 0 ||
        $diff->format("m") >= 5) {
    //more than 5 minutes have passed
}

Of course, for comparing dates, you can always compare the timestamps.


My understanding of what you need to do:

$delta = ($formated_current_date - $formated_answer_post_date) / 60; // in minutes
if ($delta < 5) {
    // show $delta
} 

EDIT: Like others pointed out, this alone will not fix all of the issues at hand. As I see it, the smallest change to your current code would be to use a date format with higher granularity - such as "Y-m-d H:i:s". This being enough, like others pointed out, is contingent on the post's date being in the same timezone as your system.


I don't see the need to do a round-trip to a string format and back, regardless of how efficient or reliable it is.

date() will default to calling time() which you can call directly and get the current time in seconds as a Unix epoch timestamp (which is what you're trying to end up with in $formated_answer_post_date). You need to look in the WordPress docs to find the equivalent based on the post's value.

Then you can do a simple comparison of seconds. 5 minutes is 300 seconds.

You will still need to check that the code can assume the timezones of both values will be the same.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜