views:

3444

answers:

4

Say I have a string coming in, "2007-02-28", what's the simplest code I could write to turn that into "2007-03-01"? Right now I'm just using strtotime(), then adding 24*60*60, then using date(), but just wondering if there is a cleaner, simpler, or more clever way of doing it.

+7  A: 

It's cleaner and simpler to add 86400. :)

The high-tech way is to do:

$date = new DateTime($input_date);
$date->modify('+1 day');
echo $date->format('Y-m-d');

but that's really only remotely worthwhile if you're doing, say, a sequence of transformations on the date, rather than just finding tomorrow.

chaos
Stupid CentOS only has PHP 5.1, and DateTime is introduced in 5.2. I guess I finally have to upgrade to an unofficial centos php package then.
davr
Er, no. Just adding 86400 is false simplicity.
staticsan
Could you explain what you mean by that?
chaos
It is quite easy to understand what 24*60*60 means at a glance. 86400 less so.
Tom Haigh
Ah. I guess I've been doing this too long, then. 86400 is as recognizable to me as 65536.
chaos
@chaos: If your smallest unit of working time is a day, then you can usually get away with adding or substracting units of 86400. If it is smaller, you need to be aware of daylight savings and time zones. In which case, use the built-in functions. They will get it right more often than you will.
staticsan
+3  A: 

A clean way is to use strtotime()

$date = strtotime("+1 day", strtotime("2007-02-28"));
echo date("Y-m-d", $date);

Will give you the 2007-03-01

Ólafur Waage
+9  A: 

You can do the addition right inside strtotime, e.g.

 $today="2007-02-28";
 $nextday=strftime("%Y-%m-%d", strtotime("$today +1 day"));
Paul Dixon
Oh, neat. Didn't know that. It's almost like good old Date::Manip.
chaos
+3  A: 

Another way is to use function mktime(). It is very useful function...

$date = "2007-02-28";
list($y,$m,$d)=explode('-',$date);
$date2 = Date("Y-m-d", mktime(0,0,0,$m,$d+1,$y));

but i think strtotime() is better in that situation...

Bajlo
nice, I didn't realise that mktime() would increment the month like that when you go over
Tom Haigh