我在日期方面遇到一些问题。我需要 make if like --->
如果您的活动少于 1 天,请考虑一下
否则,如果您的活动超过 1 天且少于 3 天,请做其他事情
否则,如果您的活动超过 3 次,请做其他事情
我需要这个 PHP 版本。我的实际代码是:
if (strtotime(strtotime($last_log)) < strtotime('-1 day') ) {
$prom .= "" . json_encode('last_activity') . ": " . json_encode("inactive less than 1 day") . ",";
} else if (strtotime($last_log) > strtotime('-1 day') && strtotime($last_log) < strtotime('-3 day')) {
$prom .= "" . json_encode('last_activity') . ": " . json_encode("inactive more than 1 day and less than 3 days") . ",";
} else if (strtotime($last_log) > strtotime('-3 day')) {
$prom .= "" . json_encode('last_activity') . ": " . json_encode("inactive more than 3") . ",";
}
我想我真的不懂日期计算。
在这种情况下
date_diff
要容易得多(http://php.net/manual/en/function.date-diff.php):
$datetime1 = date_create(); // now
$datetime2 = date_create($last_log);
$interval = date_diff($datetime1, $datetime2);
// number of days between your last login and now
$days = $interval->format('%a');
// difference (only) in days
// (2023-11-05 and 2024-01-08 will return 3 because 05 and 08 are seperated by 3 days.
$days = $interval->format('%d');
更多格式请参阅:https://www.php.net/manual/en/dateinterval.format.php
或者以你的方式:
if (strtotime($last_log) < strtotime('-1 day')){
// it's been longer than one day
}
如果你想用 strtotime 来做到这一点,请这样做:
date_default_timezone_set('SOMETHING FOR YOU');
$last_log = '-0.5 day';
$last_log_time = strtotime($last_log);
$minus1day_time = strtotime('-1 day');
$minus3day_time = strtotime('-3 day');
echo $last_log_time . "<br>";
echo $minus1day_time . "<br>";
echo $minus3day_time . "<br>";
if ($last_log_time < $minus3day_time)
{
echo "inactive more than 3";
}
elseif ( ($last_log_time <= $minus1day_time) && ($last_log_time >= $minus3day_time) )
{
echo "inactive more than 1 day and less than 3 days";
}
elseif ($last_log_time > $minus1day_time)
{
echo "inactive less than 1";
}
我从你的代码中更改了几件事:
然后应用 json_encode 注释。
解释一下为什么逻辑颠倒了:
$dateLog = new DateTime($last_log); // format if needed
$tomorrow = new DateTime("tomorrow");
$yesterday = new DateTime("yesterday");
$threeDaysAgo = new DateTime("-3 days");
if ($dateLog < $yesterday) {
// Do what you want
} else if ($dateLog > $yesterday && $dateLog < $threeDaysAgo) {
// Do another thing
} else if ($dateLog > $threeDaysAgo) {
// ...
}