PHP日期计算 [英] PHP date calculation

查看:109
本文介绍了PHP日期计算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我尝试了以下功能:

在PHP中,最好的(日期格式独立的方式)是以指定格式计算两个日期之间的差异。

  function get_date_offset($ start_date,$ end_date)
{
$ start_time = strtotime($ start_date);
$ end_time = strtotime($ end_date);
return round(($ end_time- $ start_time)/(3600 * 24));
}

它在linux框上工作正常,但在Windows下运行时,strtotime返回'



编辑



输入日期为 mm / dd / yyyy 格式,但我想让它接受$格式作为参数。



我只需要几天的差异。

解决方案

如果你不想要,或者你不能使用Zend Framework或Pear包尝试这个功能,我希望这将有助于:

 函数dateDifference($ date1,$ date2)
{
$ d1 =(is_string($ date1)?strtotime($ date1) $ date1);
$ d2 =(is_string($ date2)?strtotime($ date2):$ date2);

$ diff_secs = abs($ d1 - $ d2);
$ base_year = min(日期(​​Y,$ d1),日期(Y,$ d2));

$ diff = mktime(0,0,$ diff_secs,1,1,$ base_year);

返回数组

年=> abs(substr(日期('Ymd',$ d1) - 日期('Ymd',$ d2),0 ,
months_total=>(date(Y,$ diff) - $ base_year)* 12 + date(n,$ diff) - 1,
month=> date(n,$ diff) - 1,
days_total=> floor($ diff_secs /(3600 * 24)),
days=& (j,$ diff) - 1,
hours_total=> floor($ diff_secs / 3600),
hours=> date(G,$ diff),
minutes_total=> floor($ diff_secs / 60),
minutes=>(int)date(i,$ diff),
seconds_total=> $ diff_secs,
seconds=>(int)date(s,$ diff)
);
}


What is the best (date format independent way) in PHP to calculate difference in days between two dates in specified format.

I tried the following function:

function get_date_offset($start_date, $end_date)
{
  $start_time = strtotime($start_date);
  $end_time = strtotime($end_date);
  return round(($end_time-$start_time)/(3600*24));
}

It works ok on linux box, but when running under windows strtotime returns ''.

EDIT:

Input date is in mm/dd/yyyy format, but I would like to make it accept $format as a parameter.

I need only difference in days.

解决方案

If you do not want or you cannot use Zend Framework or Pear package try this function i hope this would help:

function dateDifference($date1, $date2)
{
    $d1 = (is_string($date1) ? strtotime($date1) : $date1);
    $d2 = (is_string($date2) ? strtotime($date2) : $date2);

    $diff_secs = abs($d1 - $d2);
    $base_year = min(date("Y", $d1), date("Y", $d2));

    $diff = mktime(0, 0, $diff_secs, 1, 1, $base_year);

    return array
    (
        "years"         => abs(substr(date('Ymd', $d1) - date('Ymd', $d2), 0, -4)),
        "months_total"  => (date("Y", $diff) - $base_year) * 12 + date("n", $diff) - 1,
        "months"        => date("n", $diff) - 1,
        "days_total"    => floor($diff_secs / (3600 * 24)),
        "days"          => date("j", $diff) - 1,
        "hours_total"   => floor($diff_secs / 3600),
        "hours"         => date("G", $diff),
        "minutes_total" => floor($diff_secs / 60),
        "minutes"       => (int) date("i", $diff),
        "seconds_total" => $diff_secs,
        "seconds"       => (int) date("s", $diff)
    );
}

这篇关于PHP日期计算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆