donglu9978 2017-08-26 12:29
浏览 104
已采纳

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.

  • 写回答

3条回答 默认 最新

  • donglu9825 2017-08-26 12:38
    关注

    I think

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

    broke your code. Try

    $got2->setTimestamp($fromdb)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器