DateTime::diff() - php 日期时间类
DateTime::diff()
DateTimeImmutable::diff
DateTimeInterface::diff
date_diff
(PHP 5 >= 5.3.0, PHP 7)
Returns the difference between two DateTime objects
说明
面向对象风格publicDateTime::diff(DateTimeInterface$datetime2[,bool $absolute=FALSE]): DateIntervalpublicDateTimeImmutable::diff(DateTimeInterface$datetime2[,bool $absolute=FALSE]): DateIntervalpublicDateTimeInterface::diff(DateTimeInterface$datetime2[,bool $absolute=FALSE]): DateInterval过程化风格
date_diff(DateTimeInterface$datetime1,DateTimeInterface$datetime2[,bool $absolute=FALSE]): DateInterval
Returns the difference between twoDateTimeInterfaceobjects.
参数
$datetimeThe date to compare to.
$absoluteShould the interval be forced to be positive?
返回值
TheDateIntervalobject representing the difference between the two dates 或者在失败时返回FALSE
.
范例
Example #1DateTime::diff()example
面向对象风格
过程化风格
以上例程会输出:
+2 days
Example #2DateTimeobject comparison
Note:As of PHP 5.2.2, DateTime objects can be compared usingcomparison operators.
以上例程会输出:
bool(false) bool(true) bool(false)
参见
- DateInterval::format() Formats the interval
- DateTime::add() 给一个 DateTime 对象增加一定量的天,月,年,小时,分钟以及秒。
- DateTime::sub() 对一个 DateTime 对象减去一定量的日、月、年、小时、分钟和秒。
It is worth noting, IMO, and it is implied in the docs but not explicitly stated, that the object on which diff is called is subtracted from the object that is passed to diff. i.e. $now->diff($tomorrow) is positive.
Be careful using: $date1 = new DateTime('now'); $date2 = new DateTime('tomorrow'); $interval = date_diff($date1, $date2); echo $interval->format('In %a days'); In some situations, this won't say "in 1 days", but "in 0 days". I think this is because "now" is the current time, while "tomorrow" is the current day +1 but at a default time, lets say: Now: 08:00pm, 01.01.2015 Tomorrow: 00:00am, 02.01.2015 In this case, the difference is not 24 hour, so it will says 0 days. Better use "today", which should also use a default value like: Today: 00:00am, 01.01.2015 Tomorrow: 00:00am, 02.01.2015 which now is 24 hour and represents 1 day. This may sound logical and many will say "of course, this is right", but if you use it in a naiv way (like I did without thinking), you can come to this moment and facepalm yourself. Conclusion: "Now" is "Today", but in a different clock time, but still the same day!
After wrestling with DateTime::diff for a while it finally dawned on me the problem was both in the formatting of the input string and the formatting of the output. The task was to calculate the duration between two date/times. ### Calculating Duration 1. Make sure you have a valid date variable. Both of these strings are valid: 2. Next convert the string to a date variable ~~~ ~~~ 3. Calculate the difference ~~~ ~~~ 4. Format the output ~~~ ~~~ [Modified by moderator for clarify]
Using the identical (===) comparision operator in different but equal objects will return false
Warning, there's a bug on windows platforms: the result is always 6015 days (and not 42...) http://bugs.php.net/bug.php?id=51184
If you want to quickly scan through the resulting intervals, you can use the undocumented properties of DateInterval. The function below returns a single number of years, months, days, hours, minutes or seconds between the current date and the provided date. If the date occurs in the past (is negative/inverted), it suffixes it with 'ago'.
It seems that while DateTime in general does preserve microseconds, DateTime::diff doesn't appear to account for it when comparing. Example: The var_dump shows that there is no "u" element, and "2 is bigger" is echoed. To work around this apparent limitation/oversight, you have to additionally compare using DateTime::format. Example:
Though I found a number of people who ran into the issue of 5.2 and lower not supporting this function, I was unable to find any solid examples to get around it. Therefore I hope this can help some others:
I needed to get the exact number of days between 2 dates and was relying on the this diff function, but found that I was getting a peculiar result with: This was returning 0 because it was exactly one month. I had to end up using : to get 30.
The result is different: Year: 00 Month: 01 Day: 00 Year: 00 Month: 00 Day: 30
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');
For those like me who don't yet have PHP 5.3 installed on their host, here's a simple alternative to get the number of days between two dates in the format '2010-3-23' or similar acceptable to strtotime(). You need PHP 5.2.
I was looking for a way to output X number of days from a given date and didn't find exactly what I was looking for. But I got this working. I hope this helps you. This will output the number of days,months, or years difference between NOW and a April 1st, 2011. If I used today, 2011-05-16 as $date1, I could return all 0's in the format. For example....
$strStart = '2013-06-19 18:25'; $strEnd = '06/21/13 21:47'; $dteStart = new DateTime($strStart); $dteEnd = new DateTime($strEnd); $dteDiff = $dteStart->diff($dteEnd); print $dteDiff->format("%H:%I:%S"); this script not comparing the date, its working only for the time
for php
Be careful when using the difference between 'Now' and a future value. Example: // imagine it is 2018-04-20 $date1 = new DateTime('now'); $date2 = new DateTime(date('Y-m-d')); $date3 = new DateTime("2018-04-30"); // future echo $date1->diff($date3)->days; // 9 days echo $date2->diff($date3)->days; // 10 days
When getting the difference between two DateTime objects with fractions of seconds, DateTime::diff() works under PHP 7.1. However, under PHP 5.6, the fraction is truncated. It's not clear whether the truncation happens when getting the DateTime objects' values, during the calculation, or immediately before returning the result.
I found that DateTime::diff isn't as accurate as I thought. I calculated the age gap between now and a birthdate from before 1970 (unix epoch). Here's what I got: Given today is January 21st, 2011: When calculating with the date() function it was more accurate (didn't use seconds/hours for comparison). Note that 3 days may be a lot if you want to create invoices and have to check against a given age to determine if the customer is chargable for taxes and so on. If someone also found this behaviour I'd like to hear about it - give me a quick mail at schindhelm (at) gmail (dot) com. Thanks.
Similar to what was mentioned by ianlenmac at gmail dot com I think its also worth mentioning to note that date_diff($datetime1, $datetime2) is equivalent to " subtract $datetime1 from $datetime2 " as opposed to thinking otherwise because of the arrangement of the arguments so date_diff($now, $tomorrow) is +ve
Another Method to compare dates: Output: The DateTimes are: d1: 07-Jun-14, 08:56 PM d2: 09-Jun-14, 09:09 PM The recent date is: 09-Jun-14, 09:09 PM The older date is: 07-Jun-14, 08:56 PM
So this function is not available for my server's PHP. I created an alternative. Convert the datetime into time-stamps, then subtract normally, then convert the seconds to whatever you want. -Suleiman ALAQEL
You don't need to calculate the exact difference if you just want to know what date comes earlier: bool(true) bool(false) bool(false)
Keep in mind that diff will convert the two DateTime objects from local time to UTC.
WARNING!!! Although you CAN directly compare DateTime objects, you will get nonintuitive results if the other object is not also DateTime compatible. I just found a subtle bug in my code because it was comparing a date against an uninitialised variable. It's better to use DateTime::diff() because the return value will only be a DateInterval object if the types were compatible, otherwise it will be false. If a DateInterval object was returned, you can check the 'invert' property to see if the second date is before the first date or not. DateInterval::invert will be 1 if the second date is before the first date, and 0 if the the second date is on or after the first date.
$dateTime = new DateTime('2011-08-01 00:00:00'); echo $dateTime->diff(new DateTime('2011-10-01 00:00:01'))->format('%m'); will return 1, instead of 2 ...
Here you have in this post http://softontherocks.blogspot.com/2014/12/calcular-la-edad-con-php.html the code to get the age of a person specifying the date of birth: function getAge($birthdate){ $adjust = (date("md") >= date("md", strtotime($birthdate))) ? 0 : -1; // Si aún no hemos llegado al día y mes en este año restamos 1 $years = date("Y") - date("Y", strtotime($birthdate)); // Calculamos el número de años return $years + $adjust; // Sumamos la diferencia de años más el ajuste }
鹏仔微信 15129739599 鹏仔QQ344225443 鹏仔前端 pjxi.com 共享博客 sharedbk.com
免责声明:我们致力于保护作者版权,注重分享,当前被刊用文章因无法核实真实出处,未能及时与作者取得联系,或有版权异议的,请联系管理员,我们会立即处理! 部分文章是来自自研大数据AI进行生成,内容摘自(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供学习参考,不准确地方联系删除处理!邮箱:344225443@qq.com)
图片声明:本站部分配图来自网络。本站只作为美观性配图使用,无任何非法侵犯第三方意图,一切解释权归图片著作权方,本站不承担任何责任。如有恶意碰瓷者,必当奉陪到底严惩不贷!
内容声明:本文中引用的各种信息及资料(包括但不限于文字、数据、图表及超链接等)均来源于该信息及资料的相关主体(包括但不限于公司、媒体、协会等机构)的官方网站或公开发表的信息。部分内容参考包括:(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供参考使用,不准确地方联系删除处理!本站为非盈利性质站点,本着为中国教育事业出一份力,发布内容不收取任何费用也不接任何广告!)