2016-08-04 75 views
1

我想添加用户定义的月份数量到以前添加的日期。 $ CustDate已经以前一种形式以YYYY-MM-DD格式存在。用户定义的月份添加到给定日期

$CustDate=$_POST['formYear'] . "-" . $_POST['formMonth'] . "-" . $_POST['formDay']; 

$months=$_POST['formMonthsAdded']; 
$d=strtotime("+" . $months . " Months"); 

$CustAddedDate=date("Y-m-d", strtotime($CustDate, $d)); 

如果我输入的日期为:2016-08-04作为$ CustDate,它给了我相同的值$ CustAddedDate。

我在哪里搞砸了?谢谢!

+0

因为你的'$ CustDate'不包含任何“相对”值,所以'$ d'中没有用于任何东西。这绝对是绝对年/月/日。 strtotime()的第二个参数为'strtotime('+ 1 day',$ some_point_in_time)'设置了一个基准时间' –

回答

2

您添加了+ months以及$CustDate。提供$Cusdate作为添加中的第二个参数。

$CustAddedDate = date('Y-m-d', strtotime("+" . $months . " Months", strtotime($CustDate))); 
                    //^add this with the addition 

还是DateTime变种:

$date = new DateTime($CustDate); 
$date->modify('+ ' . $months . ' Month'); 
$CustAddedDate = $date->format('Y-m-d'); 
echo $CustAddedDate; 
1
$CustDate=$_POST['formYear'] . "-" . $_POST['formMonth'] . "-" . $_POST['formDay']; 

$months=$_POST['formMonthsAdded']; 

$d="+" . $months . " Months"; //not strtotime time here! 

$CustAddedDate=date("Y-m-d", strtotime($d,strtotime($CustDate)));//watch the order of arguments and missing strtotime of the existing date 
2

注:

$d = strtotime('2016-03-02'); // March 2nd, 2016 -> 1456898400 

echo date('Y-m-d', strtotime('+1 day', $d)); -> 2016-03-03 
echo date('Y-m-d', strtotime('2010-01-02', $d)); -> 2010-01-02 

strtotime()第二个参数设定的时间基础,任何 “相对” 时间值,如+1 dayyesterday。由于您传递的是绝对日期,2016-08-04,因此没有任何“相对”措施可以将任何内容作为基础,并且您的绝对日期将全部用于转换。

如果要调整的是绝对日期,你必须做一些像

echo date('Y-m-d', strtotime('2016-08-04 + 1 day')) -> 2016-08-05 

例如将日期数学嵌入到传递到strtotime的字符串中,而不是在第二个参数中。

相关问题