php 使用php从日期中减去天、月或年

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20901760/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 03:39:36  来源:igfitidea点击:

Subtracting days, months or years from date using php

phpdate

提问by dimoss

I have a db table with a date field startBeforein ('Y-m-d')format. There are also 3 other int fields representing years, months and days. What I would like to do is to fill these three fields the new startAfterdate in 'Y-m-d'format.

我有一个日期字段一个数据库表startBefore('Y-m-d')的格式。还有其他 3 个 int 字段代表年、月和日。我想做的是startAfter'Y-m-d'格式填写新日期的这三个字段。

For example I have the '2001-11-14' as startBeforedate and I would like to subtract 3 yrs, 7 months, 1 day to get the startAfterdate.

例如,我将“2001-11-14”作为startBefore日期,我想减去 3 年、7 个月、1 天来获得startAfter日期。

Any ideas how I can accomplish this?

我有什么想法可以做到这一点吗?

Thanks!

谢谢!

回答by Nambi

use strtotime('date -years -months -days')

strtotime('date -years -months -days')

  <?php
    $time = strtotime('2001-11-14 -3 years -7 months -5 days');
    echo $date = date("Y-m-d", $time);

回答by tomexsans

Here comes the DateTime:

来了DateTime

$start_date = '2013-03-06';
$date = DateTime::createFromFormat('Y-m-d',$start_date);

$date->modify('+1 month');
echo $date->format('Y-m-d');//2013-04-06

$date->modify('+4 year');
echo $date->format('Y-m-d');//2017-04-06

$date->modify('+6 day');
echo $date->format('Y-m-d');//2017-04-12

$date->modify('+24 hours');
echo $date->format('Y-m-d');//2017-04-13

$date->modify('-7 years');
echo $date->format('Y-m-d'); //2010-04-13

$date->modify('-18 months');
echo $date->format('Y-m-d'); //2008-10-13

So on and so forth.

等等等等。

回答by Jenno Richi Benat

You Could try

你可以试试

strtotimefunction in php its quite simple

strtotimephp中的函数很简单

<?php 
echo date("jS F, Y", strtotime("11.12.10")); 
// outputs 10th December, 2011 

echo date("jS F, Y", strtotime("11/12/10")); 
// outputs 12th November, 2010 

echo date("jS F, Y", strtotime("11-12-10")); 
// outputs 11th December, 2010  
?> 

回答by Goikiu

One way is to make the startBefore date a timestamp, than working with numbers and re-obtain the startAfter date, another way is to try to subtract days, months and years directly from the date.

一种方法是使 startBefore 日期成为时间戳,而不是使用数字并重新获取 startAfter 日期,另一种方法是尝试直接从日期中减去天、月和年。