php 计算两个给定日期之间的月、年和日作为时间戳
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14519187/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Calculate months, years and days between two given dates as timestamp
提问by Satish Sharma
Possible Duplicate:
How to calculate the difference between two dates using PHP?
How to get difference between two dates in Year/Month/Week/Day?
i am trying to calculate years and months and days between two given dates in PHP.
我正在尝试计算 PHP 中两个给定日期之间的年月日。
i am also using timestamp of those date. is there any way to calculate years and months and
我也在使用那些日期的时间戳。有没有办法计算年份和月份
days from difference of those time stamp.
从这些时间戳的差异开始的天数。
for example first date is 2 Jan, 2008. and second one is 5 July, 2012. and result is 4 Years 5 monts and 3 days.
例如,第一个日期是 2008 年 1 月 2 日。第二个日期是 2012 年 7 月 5 日。结果是 4 年 5 个月零 3 天。
i am working on timestamp as date input and want to know that is there any function available which directly calculate above things by two input timestamp
我正在将时间戳作为日期输入工作,并想知道是否有任何可用的函数可以通过两个输入时间戳直接计算上述内容
回答by Louis Huppenbauer
You could use the DateTime object for that (please note the missing "," in the datetime constructor).
您可以为此使用 DateTime 对象(请注意 datetime 构造函数中缺少的“,”)。
$datetime1 = new DateTime('2 Jan 2008');
$datetime2 = new DateTime('5 July 2012');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%y years %m months and %d days');
回答by user1909426
You can do this pretty easily with DateTime:
您可以使用 DateTime 轻松完成此操作:
$date1 = new DateTime("2008-01-02");
$date2 = new DateTime("2012-07-05");
$diff = $date1->diff($date2);
echo "difference " . $diff->y . " years, " . $diff->m." months, ".$diff->d." days "
回答by Damien
You should have a look at Carbon, it's a pretty new PHP 5.3 lib on top of DateTime with a lot of usefull methods.
你应该看看Carbon,它是一个非常新的 PHP 5.3 库,位于 DateTime 之上,有很多有用的方法。
For Date diff:
对于日期差异:
<?php
$dtOttawa = Carbon::createFromDate(2000, 1, 1, 'America/Toronto');
$dtVancouver = Carbon::createFromDate(2013, 1, 1, 'America/Vancouver');
echo $dtOttawa->diffInHours($dtVancouver);
echo $dtOttawa->diffInDays($dtVancouver);
echo $dtOttawa->diffInMinutes($dtVancouver);
echo $dtOttawa->diffInYears($dtVancouver);
If you want Human readable diff:
如果你想要人类可读的差异:
$dt = Carbon::createFromDate(2011, 2, 1);
echo $dt->diffForHumans($dt->copy()->addMonth()); // 28 days before
echo $dt->diffForHumans($dt->copy()->subMonth()); // 1 month after
回答by Tobias
You can create two DateTime objects (www.php.net/datetime) from the timestamps. When calling the diff method you get a DateInterval object, which has properties for years and months.
您可以从时间戳创建两个 DateTime 对象 (www.php.net/datetime)。调用 diff 方法时,您将获得一个 DateInterval 对象,该对象具有年份和月份的属性。

