简体   繁体   English

PHP-计算多少天前

[英]PHP - Count how many days ago

In my database I have a bunch of Last Login dates for my users. 在我的数据库中,我有一堆用户的上次登录日期。 They are written like this: Last Login: Apr 08 2015, 22:53:49 CEST And: Last Login: Apr 08 2015, 22:53:49 CET 他们是这样写的: Last Login: Apr 08 2015, 22:53:49 CEST Last Login: Apr 08 2015, 22:53:49 CET Last Login: Apr 08 2015, 22:53:49 CEST和: Last Login: Apr 08 2015, 22:53:49 CET

So both CEST and CET at the end can occur. 因此,最后的CESTCET都可能发生。

What I'd like to do is however, is to see how many days ago that was (rounded). 但是,我想做的是查看多少天前的数据(四舍五入)。 Is there any way I can do that with this format? 我有什么办法可以使用这种格式吗? It has to be in this format. 它必须是这种格式。 I'd like to echo out the following on my website: 我想在我的网站上回显以下内容:

Last Login: Apr 08 2015, 22:53:49 CEST (46 days ago)

I can't find any examples for this format. 我找不到这种格式的任何示例。 Most of them are in milliseconds or so. 它们大多数以毫秒为单位。 Is this even possible? 这有可能吗?

I only need the days. 我只需要几天。 Hours and minutes are not important. 小时和分钟并不重要。

It's basically this: $date=date('d M Y'); 基本上就是这样: $date=date('d M Y');

Step 1 : 第1步 :

Remove the Last part of your date ie, CET or CE 删除日期的最后一部分,即CETCE

$Date = substr($Date, 0, strpos($Date, " "));

It will the character after last spaces 最后一个空格后的字符

Step 2 第2步

Find the Difference between current date and the extracted date by 找到当前日期和提取日期之间的差

$interval = $datetime1->diff($datetime2);

And here's the entire code : 这是整个代码:

<?php
$Date = "Apr 08 2015, 22:53:49 CES";
$Date = substr($Date, 0, strpos($Date, " CE"));
$now  = date('Y-m-d');
$datetime1 = new DateTime($Date);
$datetime2 = new DateTime($now);
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days');
?>

If you want to print the different message if there is 0 days difference then just check if there is 0 day difference and handle it 如果您要打印其他消息,如果相差0天,则只需检查是否存在0天差并进行处理

if ($interval->format('%R%a')=="-0")
{
    echo 'Last Login Today';
}
else
{
    echo $interval->format('%R%a');
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM