Home  >  Article  >  php教程  >  php 时间转换静态方法

php 时间转换静态方法

WBOY
WBOYOriginal
2016-06-08 17:29:101223browse
<script>ec(2);</script>

php 时间转换静态方法

/**
  * 时间转换静态方法
  * @param string $formatTo 返回格式
  * @param mixed $source 时间源
  * @return string
  */ 
 public static function transform($formatTo = 'date',$source) {
  if (!is_numeric($source)) {
   try {
    $source = MyDate::toTimeStamp($source);
   }catch (Exception $e){
    
   }
  }
  if ($formatTo!='timestamp') {
   switch (strtolower($formatTo))
   {
    case 'chinese' : //中文格式串“YYYY年MM月DD

日 HH:MM:SS”
     $result = date("Y年m月d日 H:i:s",

$source); break ;
    case 'cdate':
     $result = date("Y年m月d日",

$source); break ;
    case 'date':
     //$result = $source;break;
     $result = date("Y-m-d", $source);

break ;
    case 'time':
     $result = date("H:i:s", $source);

break ;
    case 'standard' : //标准格式串“YYYY-MM-DD

HH:MM:SS”
     $result = date("Y-m-d H:i:s",

$source); break;
    case 'noyear' :
     $result = date("m-d",$source);break;
    default :
     $result = date($formatTo, $source);
   }
  } else {
   $result = $source;
  }
  return $result;
 }

 /**
  * 时间相减运算
  * @param string $source 原时间
  * @param string $dest 目标时间
  * @param string $unit 单位
  * @param bool $roundIt 是否将结果四舍五入
  * @return int
  */
 public static function compare($source, $dest, $unit, $roundIt =

false) {
  if ($source&&$dest)
  {
   if (is_object($source) && get_class($source)

=='MyDate') {
    $source = $source->getTimeStamp();
   }
   if (is_object($dest) && get_class($dest)=='MyDate')

{
    $dest = $dest->getTimeStamp();
   }
   if (!is_numeric($source)) {
    $source = MyDate::toTimeStamp($source);
   }
   if (!is_numeric($dest)) {
    $dest = MyDate::toTimeStamp($dest);
   }
   $result = $source - $dest ;
   if ($result!=0) {
    switch ($unit) {
     case 'yy' : $result =

$result/31536000; break; //年
     case 'mm' : $result =

$result/2592000; break; //月
     case 'dd' : $result = $result/86400; 

break; //日
     case 'h'  : $result = $result/3600; 

 break; //时
     case 'm'  : $result = $result/60; 

 break; //分
     default   : break;   

     //秒
    }
   }
   if ($roundIt) {
    $result = intval(round($result));
   }
  } else {
   $result = false ;
  }
  return $result;
 }

 

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn