我有一个日期返回作为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”格式获取日期的正确方法是什么,以便它们可以在另一个查询中使用?
当前回答
下面是一个演示日期修改的小片段:
$date = date("Y-m-d");
//increment 2 days
$mod_date = strtotime($date."+ 2 days");
echo date("Y-m-d",$mod_date) . "\n";
//decrement 2 days
$mod_date = strtotime($date."- 2 days");
echo date("Y-m-d",$mod_date) . "\n";
//increment 1 month
$mod_date = strtotime($date."+ 1 months");
echo date("Y-m-d",$mod_date) . "\n";
//increment 1 year
$mod_date = strtotime($date."+ 1 years");
echo date("Y-m-d",$mod_date) . "\n";
其他回答
从PHP 5.2开始,你可以对DateTime对象使用modify:
http://php.net/manual/en/datetime.modify.php
$Date1 = '2010-09-17';
$date = new DateTime($Date1);
$date->modify('+1 day');
$Date2 = $date->format('Y-m-d');
在加上月份时要小心……(在较小的程度上,几年)
如果你使用的是PHP 5.3,你可以使用DateTime对象和它的add方法:
$Date1 = '2010-09-17';
$date = new DateTime($Date1);
$date->add(new DateInterval('P1D')); // P1D means a period of 1 day
$Date2 = $date->format('Y-m-d');
查看DateInterval构造函数手册页,了解如何构造其他时间段来添加到日期中(2天将是'P2D', 3天将是'P3D',等等)。
如果没有PHP 5.3,你应该能够像你那样使用strtotime(我已经测试过了,它在5.1.6和5.2.10中都有效):
$Date1 = '2010-09-17';
$Date2 = date('Y-m-d', strtotime($Date1 . " + 1 day"));
// var_dump($Date2) returns "2010-09-18"
另一种选择是将日期字符串转换为时间戳,然后添加适当的秒数。
$datetime_string = '2022-05-12 12:56:45';
$days_to_add = 1;
$new_timestamp = strtotime($datetime_string) + ($days_to_add * 60 * 60 * 24);
在此之后,您可以使用PHP的各种日期函数之一将时间戳转换为日期对象或将其格式化为人类可读的字符串。
$new_datetime_string = date('Y-m-d H:i:s', $new_timestamp);
要向某个日期添加特定天数,请使用以下函数。
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]
您也可以使用以下格式
strtotime("-3 days", time());
strtotime("+1 day", strtotime($date));
你可以这样堆叠更改:
strtotime("+1 day", strtotime("+1 year", strtotime($date)));
注意这种方法与其他答案之间的区别:您可以将时间戳作为strtotime的第二个参数传入,而不是将值+1 day和<timestamp>连接起来。