Andrii H.
Andrii H.

Reputation: 1812

Wrong time with DateTime

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:

  1. Get old timestamp from database. Old timestamp is the time, when a notification was sent.
  2. Get current users timestamp.
  3. Get difference between them.
  4. Echo result.

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

Answers (3)

crak
crak

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

Dmitry
Dmitry

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

HouseInTheForest
HouseInTheForest

Reputation: 96

I think

date('Y-m-d',$fromdb)

broke your code. Try

$got2->setTimestamp($fromdb)

Upvotes: 2

Related Questions