我有一个日期返回作为MySQL查询的一部分在形式2010-09-17。
我想设置变量$Date2到$Date5,如下所示:
$Date = $Date + 1
$Date = $Date + 2
从而返回2010-09-18,2010-09-19,等等。
我试过了
date('Y-m-d', strtotime($Date. ' + 1 day'))
但是这给了我$ date之前的日期。
以“Y-m-d”格式获取日期的正确方法是什么,以便它们可以在另一个查询中使用?
我有一个日期返回作为MySQL查询的一部分在形式2010-09-17。
我想设置变量$Date2到$Date5,如下所示:
$Date = $Date + 1
$Date = $Date + 2
从而返回2010-09-18,2010-09-19,等等。
我试过了
date('Y-m-d', strtotime($Date. ' + 1 day'))
但是这给了我$ date之前的日期。
以“Y-m-d”格式获取日期的正确方法是什么,以便它们可以在另一个查询中使用?
当前回答
要向某个日期添加特定天数,请使用以下函数。
function add_days_to_date($date1,$number_of_days){
/*
//$date1 is a string representing a date such as '2021-04-17 14:34:05'
//$date1 =date('Y-m-d H:i:s');
// function date without a secrod argument returns the current datetime as a string in the specified format
*/
$str =' + '. $number_of_days. ' days';
$date2= date('Y-m-d H:i:s', strtotime($date1. $str));
return $date2; //$date2 is a string
}//[end function]
其他回答
以下是对您的查询的最简单的解决方案
$date=date_create("2013-03-15"); // or your date string
date_add($date,date_interval_create_from_date_string("40 days"));// add number of days
echo date_format($date,"Y-m-d"); //set date format of the result
都必须使用以下代码:
$nday = time() + ( 24 * 60 * 60);
echo 'Now: '. date('Y-m-d') ."\n";
echo 'Next Day: '. date('Y-m-d', $nday) ."\n";
这个作品。您可以使用它的天,月,秒,并重新格式化日期根据您的要求
public function reformatDate($date, $difference_str, $return_format)
{
return date($return_format, strtotime($date. ' ' . $difference_str));
}
例子
echo $this->reformatDate('2021-10-8', '+ 15 minutes', 'Y-m-d H:i:s');
echo $this->reformatDate('2021-10-8', '+ 1 hour', 'Y-m-d H:i:s');
echo $this->reformatDate('2021-10-8', '+ 1 day', 'Y-m-d H:i:s');
您也可以使用以下格式
strtotime("-3 days", time());
strtotime("+1 day", strtotime($date));
你可以这样堆叠更改:
strtotime("+1 day", strtotime("+1 year", strtotime($date)));
注意这种方法与其他答案之间的区别:您可以将时间戳作为strtotime的第二个参数传入,而不是将值+1 day和<timestamp>连接起来。
使用变量表示天数
$myDate = "2014-01-16";
$nDays = 16;
$newDate = strtotime($myDate . '+ '.$nDays.' days');
echo new Date('d/m/Y', $newDate); //format new date