PHP 獲取時間差函數彙總

在學習PHP 的時候,經常會用到獲取現在之前或之後,某個時間段的日期。現在已經進行收集,大家同時也可以進行擴展豐富。

//獲取當天的星期(1-7)

function GetWeek($times)
{
    $res = date('w', strtotime($times));
    if($res==0)
       $res=7;
    return $res;
}
//獲取當天時間
function GetTime($times)
{
    $res = date('H:i', strtotime($times));
    return $res;
}
//獲取現在過幾月的的時間
function GetMonth($Month,$type='l')
{
    if(!strcmp($type,'b'))
      $res=date("Y-m-d H:i:s",strtotime("-$Month months"));
    if(!strcmp($type,'l'))
      $res=date("Y-m-d H:i:s",strtotime("+$Month months"));
    return $res;
}
//獲取當前時間
function GetCurrentDateTime()
{
    $res=date("Y-m-d H:i:s",time());
    return $res;
}
//獲取當前時間隔幾小時之前或之後的時間
function GetDiffHours($hours,$type='l')
{
  if(!strcmp($type,'b'))
     $res=date("Y-m-d H:i:s",strtotime("-$hours hour"));
  if(!strcmp($type,'l'))
     $res=date("Y-m-d H:i:s",strtotime("+$hours hour"));
  return $res;     
}
//間隔幾分鐘之前或之後的時間
function GetDiffMinute($Minute,$type='l')
{
  if(!strcmp($type,'b'))
     $res=date("Y-m-d H:i:s",strtotime("-$Minute minute"));
  if(!strcmp($type,'l'))
     $res=date("Y-m-d H:i:s",strtotime("+$Minute minute"));
  return $res;     
}
//間隔幾秒之前或之後的時間
function GetDiffSec($sec,$type='l')
{
  if(!strcmp($type,'b'))
     $res=date("Y-m-d H:i:s",strtotime("-$sec second"));
  if(!strcmp($type,'l'))
     $res=date("Y-m-d H:i:s",strtotime("+$sec second"));
  return $res;     
}

//間隔幾個星期之前或之後的時間
function GetDiffWeek($Week,$type='l')
{
  if(!strcmp($type,'b'))
     $res=date("Y-m-d H:i:s",strtotime("-$Week week"));
  if(!strcmp($type,'l'))
     $res=date("Y-m-d H:i:s",strtotime("+$Week week"));
  return $res;     
}
// 間隔幾天之間的時間
function GetDiffDays($days,$type='l')
{
  if(!strcmp($type,'b'))
     $res=date("Y-m-d H:i:s",strtotime("-$days day"));
  if(!strcmp($type,'l'))
     $res=date("Y-m-d H:i:s",strtotime("+$days day"));
  return $res;     
}
//間隔幾年之前或之後的時間
function GetDiffYears($year,$type='l')
{
  if(!strcmp($type,'b'))
     $res=date("Y-m-d H:i:s",strtotime("-$year year"));
  if(!strcmp($type,'l'))
     $res=date("Y-m-d H:i:s",strtotime("+$year year"));
  return $res;     
}

通過進行函數封裝之後,很容易從詞義上去理解函數的作用,不用記憶太多的關鍵字的拼寫問題。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章