Reputation: 1812
I am creating notifications system and here is a task: get the time, when a notification was sent. I mean the following: 1 minute ago, 13 hours ago and so on. I have already made up a script but it shows wrong time. For example instead of showing '5 minutes ago' it shows '9 hours ago'. Here is the alrogithm:
Here is the PHP code:
$fromdb = '1503737539'; //For this example think, that this variable is from database.
//This timestamp was created 5 minutes earlier, so in result it should show '5 minutes ago'.
$curr = new DateTime();
$got2 = new DateTime(date('Y-m-d H:i:s',$fromdb));
$interval = $curr->diff($got2);
echo $interval->format('%d')." days ".$interval->format('%h')." Hours ".$interval->format('%i')." Minutes ".$interval->format('%s')." Seconds";
The output is:
0 days 9 hours ....
instead of
0 days 0 hours 5 minutes ....
How can I fix that? I guess that this is a problem with timezones. But how can I guess guests timezone though?
Update: Change code: $got2 = new DateTime(date('Y-m-d H:i:s',$fromdb));
And interesting fact: The more is actual difference, the less time it shows in output. For example: Old timestamp was created at 8:00 am, and current is 15:00 pm, it shows 0 days 1 hour in output.
Upvotes: 0
Views: 1848
Reputation: 48
Try
$date = new DateTime(); echo $date->format('U = Y-m-d H:i:s');
$date->setTimestamp(1171502725); echo $date->format('U = Y-m-d H:i:s');
Upvotes: 1
Reputation: 499
there is mistake in your code. you format date without hours, minutes and seconds
$got2 = new DateTime(date('Y-m-d',$fromdb));
try
$got2 = new DateTime(date('Y-m-d H:i:s',$fromdb));
Upvotes: 1
Reputation: 96
I think
date('Y-m-d',$fromdb)
broke your code. Try
$got2->setTimestamp($fromdb)
Upvotes: 2