DateTime::add() - php 日期时间类
DateTime::add()
date_add
(PHP 5 >= 5.3.0, PHP 7)
给一个 DateTime 对象增加一定量的天,月,年,小时,分钟以及秒。
说明
面向对象风格publicDateTime::add(DateInterval$interval): DateTime过程化风格
date_add(DateTime$object,DateInterval$interval): DateTime
将给定的DateInterval对象加到DateTime对象上。
参数
$object仅过程化风格:由date_create()返回的DateTime类型的对象。此函数会修改这个对象。
$intervalDateInterval对象。
返回值
返回被修改的 DateTime 对象,或者在失败时返回FALSE
.
范例
Example #1DateTime::add()例程
面向对象风格
过程化风格
以上例程会输出:
2000-01-11
FurtherDateTime::add()例程
以上例程会输出:
2000-01-01 10:00:30 2007-06-05 04:03:02
当在 DateTime 上加月的时候要注意
以上例程会输出:
2001-01-31 2001-03-03
注释
在 PHP 5.2 的版本中,也可以使用DateTime::modify()方法来替代本方法。
参见
- DateTime::sub() 对一个 DateTime 对象减去一定量的日、月、年、小时、分钟和秒。
- DateTime::diff() Returns the difference between two DateTime objects
- DateTime::modify() 修改日期时间对象的值
Note that the add() and sub() methods will modify the value of the object you're calling the method on! This is very untypical for a method that returns a value of its own type. You could misunderstand it that the method would return a new instance with the modified value, but in fact it modifies itself! This is undocumented here. (Only a side note on procedural style mentions it, but it obviously does not apply to object oriented style.)
Another simple solution to adding a month but not autocorrecting days to the next month is this. (Also works for substracting months) $dt = new DateTime("2016-01-31"); $oldDay = $dt->format("d"); $dt->add(new DateInterval("P1M")); // 2016-03-02 $newDay = $dt->format("d"); if($oldDay != $newDay) { // Check if the day is changed, if so we skipped to the next month. // Substract days to go back to the last day of previous month. $dt->sub(new DateInterval("P" . $newDay . "D")); } echo $dt->format("Y-m-d"); // 2016-02-29 Hope this helps someone.
If you're using PHP >= 5.5, instead of using "glavic at gmail dot com"'s DateTimeEnhanced class, use the built in DateTimeImmutable type. When you call DateTimeImmutable::add() it will return a new object, rather than modifying the original
Here is a solution to adding months when you want 2014-10-31 to become 2014-11-30 instead of 2014-12-01.
If you need add() and sub() that don't modify object values, you can create new methods like this:
If you use fraction of seconds, you may have surprises. It only occurs when the sum of the floating point parts results in exactly 1 second (0.5 + 0.5 ou 0.3 + 0.7, for example). See these cases at intervals slightly bigger than 1 second: $strDataHora is correct: "2017-12-31T23:59:59.900" $strDataHora is correct: "2018-01-01T00:00:00.100" But... $strDataHora has "2017-12-31T23:59:59.1000" To resolve, add 1 second to the interval and f property must be negative (-1.0 plus original value): $strDataHora is correct: "2018-01-01T00:00:00.000"
What you can do with this function/method is a great example of the philosophy: "just because you can do it doesn't mean you should". I'm talking about two issues: (1) the number of days in the month which varies from months 1-12 as well as for month 2 which could be leap year (or not); and then issue (2): what if there is the need to specify a large quantity of an interval such that it needs to be re-characterized into broader-scoped intervals (i.e. 184 seconds ==> 3 minutes-4 seconds). Examples in notes elsewhere in the docs for this function illustrate both issues and their undesired effects so I won't focus on them further. But how did I decide to handle? I've gone with four "public" functions and a single "private" function, and without giving you a bunch of code to study, here are their summaries... 1. function adjustYear(int $yearsAdj){ //you can pass in +/- value and I adjust year value by that value but then I also call PHP's 'cal_days_in_month' function to ensure the day number I have in my date does not exceed days in the month for the new year/month combo--if it does, I adjust the day value downward. 2. function adjustMonth(int $monthsAdj){ //same notes as above apply; but also, I allow any number to be passed in for $monthsAdj. I use the 'int' function (int($monthsAdj/12)) and modulus % operator to determine how to adjust both year and month. And again, I use 'cal_days_in_month' function to tweak the day number as needed. 3. function addTime(int $days, int $hours, int $minutes, int $seconds){ // I use date_add and create a DateInterval object from the corresponding string spec (created from the args passed to this function). Note that months and years are excluded due to the bad side-effects already mentioned elsewhere. 4. function subtractTime(int $days, int $hours, int $minutes, int $seconds){ //notes for "addTime" also apply to this function but note that I like separate add and subtract functions because setting the DateInterval property flag to indicate add/subtract is not as intuitive for future coding. 5. function recharacterizeIntervals(int $days, int $hours, int $minutes, int $seconds){ // I convert excessively large quantities of any one interval into the next largest interval using the 'int' function and modulus (%) operator. I then use the result of this function when creating the string interval specification that gets passed when generating the DateInterval object for calling the date_add function (or object-method equivalent). **Results/goals... --any number of days/hours/minutes/seconds can be passed in to add/subtractTime and all of "Y/M/D/H/M/S" values get adjusted as you would expect. --using adjustYear/Month lets you pass +/- values and only "Y/M" values get modified without having undesirable effects on day values. --a call to the "recharacterize" function helps ensure proper and desired values are in the intervals prior to calling date_add to let it do its work.
Be careful when using this function, I may have happened upon a bug in PHP7. My code is as follows //get date from post or else fill with today's date if (isset($_POST["from"])) { $from = date_create($_POST["from"]); }else{ $from = date_create(date("Y-m-d")); } //get date from post if there isn't one just take the same date as what is in the $from variable and add one day to it if (isset($_POST["to"])) { $to = date_create($_POST["to"]); }else{ $to = $from; date_modify($to, '+1 day'); } echo(date_format($from, 'Y-m-d') . " " . date_format($to, 'Y-m-d')); The resultant output is $from = 2015-12-11 $to = 2015-12-11 In actuality the result should be $from = 2015-12-10 $to = 2015-12-11 For some reason the code above modifies the $from variable in the line date_modify($to, '+1 day'); even though it shouldn't as the $from variable isn't being modified. to fix this i needed to change the code to //get date from post or else fill with today's date if (isset($_POST["from"])) { $from = date_create($_POST["from"]); }else{ $from = date_create(date("Y-m-d")); } //get date from post if there isn't one just take the same date as what is in the $from variable and add one day to it if (isset($_POST["to"])) { $to = date_create($_POST["to"]); }else{ $to = date_create(date("Y-m-d")); date_modify($to, '+1 day'); } echo(date_format($from, 'Y-m-d') . " " . date_format($to, 'Y-m-d')); This isn't strictly the code I wanted. Possible bug?
adding 15 min to a datetime period: P1Y2M3DT1H2M3S period time: PT1H2M3S
鹏仔微信 15129739599 鹏仔QQ344225443 鹏仔前端 pjxi.com 共享博客 sharedbk.com
免责声明:我们致力于保护作者版权,注重分享,当前被刊用文章因无法核实真实出处,未能及时与作者取得联系,或有版权异议的,请联系管理员,我们会立即处理! 部分文章是来自自研大数据AI进行生成,内容摘自(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供学习参考,不准确地方联系删除处理!邮箱:344225443@qq.com)
图片声明:本站部分配图来自网络。本站只作为美观性配图使用,无任何非法侵犯第三方意图,一切解释权归图片著作权方,本站不承担任何责任。如有恶意碰瓷者,必当奉陪到底严惩不贷!
内容声明:本文中引用的各种信息及资料(包括但不限于文字、数据、图表及超链接等)均来源于该信息及资料的相关主体(包括但不限于公司、媒体、协会等机构)的官方网站或公开发表的信息。部分内容参考包括:(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供参考使用,不准确地方联系删除处理!本站为非盈利性质站点,本着为中国教育事业出一份力,发布内容不收取任何费用也不接任何广告!)