如何减去两个日期,忽略PHP中的夏令时? [英] How to subtract two dates, ignoring daylight savings time in PHP?

查看:130
本文介绍了如何减去两个日期,忽略PHP中的夏令时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图计算两天之间的天数,但是我遇到了夏令时间的问题。这是我的代码:

I'm trying to calculate the number of days between two days, but I'm running into issues with Daylight Savings Time. Here's my code:

function date_diff($old_date, $new_date) {
    $offset = strtotime($new_date) - strtotime($old_date);
    return $offset/60/60/24;
}

只要日期都在相同的DST期间, / p>

Works fine as long as the days are both within the same DST period:

echo date_diff('3/15/09', '3/18/09'); // 3

但是如果他们分开,则不是:

But not if they're further apart:

echo date_diff('11/15/08', '3/18/09'); // 122.95833333333

我想要几天,而不在乎DST。我想我可以舍弃结果,但是感觉到k。。有更好的(容易)的方式吗?我不想写一整天的解析和计数避免闰年的东西,如果我可以避免。

I want an even number of days, and don't care about DST. I suppose I could round the result, but that feels kludgy. Is there a better (easy) way? I don't want to have to write a whole day-parsing-and-counting-avoiding-leap-years thing if I can avoid it.

(注意:这个必须在php 5.1.6下运行,所以5.3中的某些日期功能可能无法使用。)

(Note: this has to run under php 5.1.6, so some of the date features in 5.3 may not be available.)

更多信息:我要采取偏移并将其添加到数据库中的其他数据时间,我只想要更改日期部分,而不是时间部分。反正四舍五入不行,无论如何,因为当我加入时,在另一个方向上下了一个小时。也许对整个问题有一个更好的方法....

A bit more info: I'm going to take the offset and add it to other datetimes that are in a db, and I want only the day part to change, not the time part. Turns out rounding won't work, anyway, because when I do the adding it gets off by one hour in the other direction. Maybe there's a better approach to the whole problem....

推荐答案

你可以使用 http://ca3.php.net/date_default_timezone_set 将时区设置为GMT,所以不会有偏移。

you could use http://ca3.php.net/date_default_timezone_set to set the timezone to GMT so there will be no offset.

另外,您可以使用日期('I',$ timetamp)手动添加一个偏移量

if ( date("I") == 1 ) {      // "WE ARE MDT";  
        $timeZone = "MDT";  
} else {  
        $timeZone = "MST";  
}  

这篇关于如何减去两个日期,忽略PHP中的夏令时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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