i've got little problem here. I recieve reg_time from database in this format: Y-m-d H:i:s (2020-08-26 13:50:11) and i want to compare it with current time: $today = date("Y-m-d H:i:s"); Is there any function for it? THX
Asked
Active
Viewed 321 times
1
-
1You can ask the DB to deliver for instance `SELECT *, TIMESTAMPDIFF(MINUTE, datefield, NOW() AS diffMinutes`. See [Timestampdiff](https://www.w3resource.com/mysql/date-and-time-functions/mysql-timestampdiff-function.php). – Markus Zeller Aug 27 '20 at 14:31
-
You can use [strtotime()](https://www.php.net/manual/en/function.strtotime.php) to convert these to unix timestamps (seconds) and then can just subtract to get the difference. And `/ 60` to convert to minutes, etc. `$diff = strtotime("2020-08-26 13:50:11") - time();` – WOUNDEDStevenJones Aug 27 '20 at 14:39
-
1Does this answer your question? [Comparing timestamp to current time from database](https://stackoverflow.com/questions/14647338/comparing-timestamp-to-current-time-from-database) – BadHorsie Aug 27 '20 at 14:42
2 Answers
1
There's a package called Carbon, it's very useful for date manipulation. For your use case looks like it could be solved using a method called diffForHumans()
So, the full example would be:
Carbon::parse('2020-08-26 13:50:11')->diffForHumans();
The output would be 1 day ago
Edit:
The question was fully rewritten

Vladan
- 1,572
- 10
- 23
1
The DateTime
and DateInterval
classes are intended for this:
<?php
$timeInput = '2020-08-26 13:50:11';
$origin = new DateTime($timeInput);
$target = new DateTime();
$interval = $origin->diff($target);
echo $interval->format('Registered %y years, %m months, %d days, %h hours, %i minutes, %s seconds ago').PHP_EOL;

Rob Ruchte
- 3,569
- 1
- 16
- 18
-
-
btw, can i do something like if ($interval->format(%m)==0)? can i operate it somehow – Štěpán Karlovec Aug 27 '20 at 17:43
-
Yes, if you just use a single format field like that it will just return a number that you can operate on. Just be sure you understand what DateInterval returns - if the interval has 35 days, you would get something like 1 month, 5 days, not the total number of days. – Rob Ruchte Aug 27 '20 at 18:09