简体   繁体   English

PHP中两个日期之间的差异

[英]Difference between two dates in months in php

I am trying to get the difference between two months. 我正在努力弄清两个月之间的差额。 For instance for below, I would want 2 months. 例如下面,我要两个月。

$datetime1 = date_create('2017-03-01');
$datetime2 = date_create('2017-04-30');
$interval = date_diff($datetime1, $datetime2);
echo $interval->format('%m months');
echo $interval->format('%d days');

This gives me 2 months and 1 day. 这给了我2个月零1天的时间。

The reason why you're getting an incorrect result is most likely because you haven't set a default timezone, one for "your" timezone. 结果不正确的原因很可能是因为您尚未设置默认时区,即“您的”时区。

In adding and for example: 以添加为例:

date_default_timezone_set('America/New_York');

returned the correct time difference, while not using it returned what you are presently getting. 返回正确的时差,不使用时返回您当前得到的时间。

Use the one for your own timezone, or set it in your system file(s). 使用一个作为您自己的时区,或在您的系统文件中进行设置。

From the manual http://php.net/manual/en/datetime.diff.php under "User Contributed Notes": 在手册“用户贡献的注释”下的http://php.net/manual/zh/datetime.diff.php中

"When using datediff make sure your time zone is correct, for me on Windows 7 64 bit it behaved very strange when timezone was wrong (I was comparing now against time in database and exif metadata in photos). For example: date_default_timezone_set('Europe/Oslo');" “使用datediff时,请确保您的时区正确,对我来说,在Windows 7 64位上,当时区错误时,它的表现非常奇怪(我现在将其与照片中的数据库和exif元数据中的时间进行比较)。例如:date_default_timezone_set('Europe / Oslo');“

and go through the rest of "User Contributed Notes". 并阅读“用户贡献的笔记”的其余部分。

  • Another possible reason would be the server's location which is different from "your" position on "earth". 另一个可能的原因是服务器的位置与“地球”上“您”的位置不同。

Relevant link from comments given by RiggsFolly: RiggsFolly提供的评论的相关链接:

which could be at play here. 这可能在这里发挥作用。


Edit: 编辑:

After noticing the OP accepting this answer, taken from a comment by RiggsFolly was to also add: 在注意到OP接受了这个答案之后,RiggsFolly的评论中还添加了:

date_default_timezone_set('UTC');

I would call this a joint venture and I can't take full credit for this. 我称这是一家合资企业,对此我不能称赞。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM