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

将本地时间响应转换为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?

图片转代码服务由CSDN问答提供 功能建议

我需要获取自1970年以来的秒数,直到我调用 localtime 。 有没有一种简单的方法将从 localtime(1393340639)返回的内容转换回秒?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

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.

    点赞 打赏 评论
  • doukeng7426 2014-02-25 15:10

    If you're looking for number of seconds from 1970 till a function being called, you can use <?PHP echo time() ?>

    点赞 打赏 评论

相关推荐 更多相似问题