How can I get a date after 15 days/1 month in PHP?
Asked Answered
D

6

23

In my PHP code I have a date in my variable "$postedDate".
Now I want to get the date after 7 days, 15 days, one month and 2 months have elapsed.

Which date function should I use?

Output date format should be in US format.

Depressive answered 6/5, 2009 at 6:48 Comment(1)
The term you want to Google for is "date arithmetic".Israelisraeli
A
35

Use strtotime.

$newDate = strtotime('+15 days',$date)

$newDate will now be 15 days after $date. $date is unix time.

http://uk.php.net/strtotime

Assembler answered 6/5, 2009 at 7:22 Comment(0)
H
18

try this

$date = date("Y-m-d");// current date

$date = strtotime(date("Y-m-d", strtotime($date)) . " +1 day");
$date = strtotime(date("Y-m-d", strtotime($date)) . " +1 week");
$date = strtotime(date("Y-m-d", strtotime($date)) . " +2 week");
$date = strtotime(date("Y-m-d", strtotime($date)) . " +1 month");
$date = strtotime(date("Y-m-d", strtotime($date)) . " +30 days");
Hewlett answered 6/5, 2009 at 6:52 Comment(0)
G
16

Since PHP 5.2.0 the DateTime build in class is available

$date = new DateTime($postedDate);

$date->modify('+1 day');

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

http://php.net/manual/en/class.datetime.php

Gothurd answered 25/11, 2012 at 19:49 Comment(1)
I always prefer this solution over strtotime option.Pronunciamento
E
11
$date=strtotime(date('Y-m-d'));  // if today :2013-05-23

$newDate = date('Y-m-d',strtotime('+15 days',$date));

echo $newDate; //after15 days  :2013-06-07

$newDate = date('Y-m-d',strtotime('+1 month',$date));

echo $newDate; // after 1 month :2013-06-23
Exceptive answered 23/5, 2013 at 13:12 Comment(0)
T
4

This is very simple; try this:

$date = "2013-06-12"; // date you want to upgade

echo $date = date("Y-m-d", strtotime($date ." +1 day") );
Torch answered 22/5, 2013 at 17:50 Comment(0)
H
3

What’s the input format anyway?

1) If your date is, say, array of year, month and day, then you can mktime (0, 0, 0, $month, $day + 15, $year) or mktime (0, 0, 0, $month + 1, $day, $year). Note that mktime is a smart function, that will handle out-of-bounds values properly, so mktime (0, 0, 0, 13, 33, 2008) (which is month 13, day 33 of 2008) will return timestamp for February, 2, 2009.

2) If your date is a timestamp, then you just add, like, 15*SECONDS_IN_A_DAY, and then output that with date (/* any format */, $postedDate). If you need to add one month 30 days won’t of course always work right, so you can first convert timestamp to month, day and year (with date () function) and then use (1).

3) If your date is a string, you first parse it, for example, with strtotime (), then do whatevee you like.

Healall answered 6/5, 2009 at 8:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.