PHP通过时间戳获取时间段


PHP get time period by timestamp

如何通过给定的时间戳获取时间段(日、周、月)?我不想约会。我希望下一个时间段基于秒数。

是否有一个PHP本地函数?

的例子:

$period = getTimeperiod( 15638400 );

我的尝试:我可以检查和数秒:

if x <= 60 => min
if x <= 60*60 => hour
if x <= 60*60*24 => day
...
编辑:

时间段是指分钟、小时、天、周、…如上所述……? !所以我想要的是时间戳对应的时间段

示例:(day = 86400 secs)那么带getTimeperiod( 85000 )的时间戳应该是"day"

我想你是在寻找类似于类DateInterval…

它是PHP的一部分,因为5.3.0和有一个静态函数称为createFromDateString(),你可以从一个字符串,如"3600秒"设置一个日期间隔。从这个对象中,你可以得到日、月、年等等。

看看这一页:http://www.php.net/manual/de/dateinterval.createfromdatestring.php

但是这是否在返回区间对象(周期)的正确路径上?感谢@ simmonsimcity指出了DateInterval。如果你指导我,我可以改进答案。

<?php 
$timestamp = 15638400;
echo "The timestamp $timestamp is " . date("Y-m-d H:i:s", 15638400) . "<br '>";
echo "<pre>";
print_r  (DateInterval::createFromDateString(date("Y ''y''e''a''r''s m ''m''o''n''t''h''s d ''d''a''y''s'' H ''h''o''u''r''s i ''m''i''n''u''t''e''s s ''s''e''c''o''n''d''s", 15638400 ) ) );
echo "</pre>"
?>

输出

The timestamp 15638400 is 1970-07-01 00:00:00
DateInterval Object
(
    [y] => 1970
    [m] => 7
    [d] => 1
    [h] => 0
    [i] => 0
    [s] => 0
    [invert] => 0
    [days] => 0
)

我是这样解决的:

  /*
  seconds     0
  minutes     1
  hours       2
  days        3
  week        4
  month       5
  year        6
  decade      7
  century     8
  millenium   9
  */
  $arTimes = array(
     0 => 1,
     1 => 60,
     2 => 60*60,
     3 => 60*60*24,
     4 => 60*60*24*7,
     5 => 60*60*24*7*4,
     6 => 60*60*24*7*4*12,
     7 => 60*60*24*7*4*12*10,
     8 => 60*60*24*7*4*12*10*10,
     9 => 60*60*24*7*4*12*10*10*10
  );
  $nDiff = strtotime( $nTo ) - strtotime( $nFrom );
  switch( $nDiff )
  {
     // check difference and time period
     case $nDiff <= $arTimes[ 1 ]:
        $nGranularity = 0;
        break;
     ...
  }