meleyal
meleyal

Reputation: 33270

How to calculate a relative date based on a date string

I'd like to find the date after a date provided by the user

This is not working:

$start_date = '2009-06-10';

$next_day = date( $start_date, strtotime('+1 day') );     

echo $next_day; // 2009-06-10

Upvotes: 0

Views: 588

Answers (3)

VVS
VVS

Reputation: 19604

$start_date = '2009-06-10';
$next_day = new DateTime($start_date)->modify("+1 day")->format("Y-m-d"); 

EDIT:

As Kristina pointed out this method doesn't work since DateTime::modify doesn't return the modified date as I suspected. (PHP, I hate your inconsistency!)

This code now works as expected and looks IMHO a little bit more consistent than date_modify :)

$start_date = '2009-06-10';

$next_day = new DateTime($start_date);
$next_day->modify("+1 day")

echo $next_day->format("Y-m-d"); 

Upvotes: 0

meleyal
meleyal

Reputation: 33270

$start_date = '2009-06-10';

$next_day = date( 'Y-m-d', strtotime( '+1 day', strtotime($start_date) ) );

echo $next_day; // 2009-06-11

Upvotes: 1

kris
kris

Reputation: 23592

Try date_modify:

$d = new DateTime("2009-01-01"); 
date_modify($d, "+1 day"); 
echo $d->format("Y-m-d");

Documentation at https://www.php.net/manual/en/datetime.modify.php.

Upvotes: 2

Related Questions