从时间戳 (PHP) 获取 +30 天


Get +30 days from timestamp (PHP)

这是我的代码:

$graceperiod = strtotime("+30 day","23-12-2013");
echo $graceperiod;

我得到以下输出:

Sat, 31 Jan 1970 00:00:23 GMT

年份错了。知道为什么它没有正确转换吗?

strtotime 是一个"危险"的函数,如果你不知道它到底做了什么。你应该这样尝试

strtotime('+30 days', $timestamp);

其中$timestamp是实际的时间戳,因为它不像您希望的那样可靠

>strtotime将Unix时间戳作为其第二个参数,因此您需要先对其进行转换。

以下内容具有正确的输出:

$graceperiod = date("Y-m-d", strtotime("+30 days",strtotime("23-12-2013")));
echo $graceperiod;

您可以使用旧的 strtotime() 函数(它接受时间戳作为第二个参数)或使用DateTime类:

使用strtotime()

$format = 'd-m-Y';
$timestamp = strtotime( "+30 day",strtotime( "23-12-2013" ) );
echo date( $format, $timestamp );

使用DateTime类:

$dateTime = DateTime::createFromFormat( $format, '23-12-2013' );
$dateTime->add( new DateInterval( 'P30D' ) );
echo $dateTime->format( $format );

这里的P30D是指 30 天的期限

使用 DateTime 的一个优点是您可以定义自己的格式,而不是从接受的格式列表中使用strtotime()

更改

$graceperiod = strtotime("+30 day","23-12-2013");

$graceperiod = strtotime("+30 days","23-12-2013");

30 days是正确的,而不是30 day

参考

strtotime将第二个参数计作为时间戳,因此您应该执行以下操作:

$graceperiod = strtotime("+30 day", strtotime("23-12-2013"));
echo date("Y-m-d H:i:s", $graceperiod);

尝试以下代码。

$date = "23-12-2013";
$graceperiod = date("Y-m-d", strtotime("+30 days",strtotime($date)));
echo $graceperiod;
strtotime("next month");

date('Y-m-d', strtotime("+30 days"));

代码:

$graceperiod = strtotime('23-12-2013 +30 day');
var_dump(date('Y-m-d', $graceperiod));

结果:

string(10) "2014-01-22"