dongroufan6846 2014-02-25 15:06
浏览 220
已采纳

将本地时间响应转换为1970年以来的秒数[关闭]

I need to get the number of seconds since 1970 untill the time I got after calling localtime. Is there a simple way to convert what is returning from localtime (1393340639) for example back to seconds?

  • 写回答

2条回答 默认 最新

  • doutongfu9484 2014-02-25 15:22
    关注

    Do not use localtime. Since PHP 5.2 was release, back last November 2nd 2006, you can use DateTime which offers a better interface to play with time, and which is compatible with UNIX timestamps (what you're looking for).

    ** Edit **

    For example :

    // always work with UTC!
    date_default_timezone_set('UTC');
    
    // support your legacy need...
    $lt = localtime(1393340639);
    
    $dt = new DateTime();
    // Note : DateTime's year is 0 based, while localtime's 1900 based, so we add 1900
    // Note : DateTime's month is 1 based, while localtime's 0 based, so we add 1
    $dt->setDate($lt[5] + 1900, $lt[4] + 1, $lt[3]);
    $dt->setTime($lt[2], $lt[1], $lt[0]);
    //$dt->setTimestamp(1393340639);  // <-- SAME THING!
    
    var_dump($dt);
    // output:
    // object(DateTime)#1 (3) {
    //  ["date"]=>
    //  string(19) "2014-02-25 15:03:59"
    //  ["timezone_type"]=>
    //  int(3)
    //  ["timezone"]=>
    //  string(3) "UTC"
    // }
    
    echo $dt->getTimestamp();
    // output: 1393340639 (which is your initial timestamp value)
    

    You're better off not using localtime altogether, though. Just pass a DateTime object around.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看