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
2009-03-18 23:35:06
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
2009-03-18 23:45:25
Er, no. Just adding 86400 is false simplicity.
staticsan
2009-03-19 04:35:34
Could you explain what you mean by that?
chaos
2009-03-19 04:52:27
It is quite easy to understand what 24*60*60 means at a glance. 86400 less so.
Tom Haigh
2009-03-19 11:08:11
Ah. I guess I've been doing this too long, then. 86400 is as recognizable to me as 65536.
chaos
2009-03-19 13:28:15
@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
2009-03-23 22:16:16
+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
2009-03-18 23:41:39
+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
2009-03-18 23:42:48
+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
2009-03-19 00:48:58
nice, I didn't realise that mktime() would increment the month like that when you go over
Tom Haigh
2009-03-19 11:10:59