简体   繁体   English

如何在PHP中延长日期?

[英]How to extend date in PHP?

I have developed a subscription website. 我已经开发了一个订阅网站。 I am facing php date extend problem. 我面临着php日期延长问题。

Please read my message- 请阅读我的留言-

Suppose today i have subscribe a package. 假设今天我已经订阅了一个软件包。 Package duration 1 month. 套餐有效期1个月。 I mean 2014-05-08 to 2014-06-07 我的意思是2014-05-08至2014-06-07

After two days i will again subscribe this same package. 两天后,我将再次订阅同一套软件包。 now the Package duration will extend 2014-06-07 to 2014-07-07 现在,套餐有效期将从2014-06-07延长至2014-07-07

In my PHP code i am getting current date to +1 month but how to get after 1 month to next one month? 在我的PHP代码中,我将当前日期更新为+1个月,但是如何在1个月后更新到下个月?

I have used this code: 我使用了以下代码:

date('Y-m-d h:i:s', mktime(0, 0, 0, date("m")+$getSubscription['Subscription']['duration'], date("d"), date("Y")));

You can use strtotime to achieve this. 您可以使用strtotime来实现。

Check this out: 看一下这个:

<?php

// current subscription expiry date
$day = '2014-06-07';

// add 30 days to the date above
$new_date = date('Y-m-d', strtotime($day . " +30 days"));

// debug
echo $new_date;

Outputs: 2014-07-07 产出: 2014-07-07

Ps are you saving the newly calculated date into db or something and then using it on the next calculation? 附言:您是否将新计算的日期保存到db或其他内容中,然后在下一次计算中使用它?

Or use the DateTime object : 或使用DateTime对象:

<?php

$date = new DateTime('2014-06-07');
$date_end = clone $date;
$date_end->add(new DateInterval('P1M');

echo $date_end->format('Y-m-d');

You'd save yourself a lot of hassle by using DateTime objects instead of messing around with date() and mktime(). 通过使用DateTime对象,您可以节省很多麻烦,而不是麻烦于date()和mktime()。 In order to get today, simply: 为了获得今天,只需:

$subscriptionDate = new DateTime(); // 2014-05-08

Then you can use the DateInterval class to add additional months, so if it's a monthly subscription, simply: 然后,您可以使用DateInterval类添加其他月份,因此,如果是每月订阅,则只需:

$subscriptionPeriod = new DateInterval('P1M');
$subscriptionDate->add($subscriptionPeriod);

Now, $subscriptionDate will be at 2014-06-08. 现在, $subscriptionDate将在2014-06-08。 You can keep adding as many months as you want and save it to your database, in the format you want, like: 您可以根据需要继续添加任意多个月,并将其以所需的格式保存到数据库中,例如:

$subscriptionDate->format('Y-m-d'); // 2014-06-08
$subscriptionDate->format('Y-m-d H:i:s'); // incl. time, e.g. 2014-06-08 12:02:45

See the manual for more examples. 有关更多示例,请参见手册

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM