-1

Possible Duplicate:
Format mysql datetime with php

I want to calculate for example 10 days after a given date, it's easy when it's in "Y-m-d" format using strtotime, but in my case, I'm reading the given date from mysql which is in "Y-m-d H:i:s" format, now strtotime seems to not working on such date formats.

How I could calculate 10 days after a given date in "Y-m-d H:i:s" format?

Thank you in advance, Behzad

Community
  • 1
  • 1
behz4d
  • 1,819
  • 5
  • 35
  • 59
  • 1
    Take a look at [`DateTime`](http://ir2.php.net/manual/en/book.datetime.php) – Leri Sep 06 '12 at 14:42
  • 1
    This is *not a duplicate* of the referenced question, that one talks only about formatting, this is about math. This inaccurate moderation is slowly taking all the fun out of SO – Kris Sep 06 '12 at 20:46

2 Answers2

4

Use DateTime to modify the date to add 10 days:

$date = DateTime::createFromFormat( 'Y-m-d H:i:s', $string);
$date->modify( '+10 days');
echo $date->format( 'Y-m-d H:i:s');
nickb
  • 59,313
  • 13
  • 108
  • 143
  • +1, good answer _and_ exactly what I would do in cases where doing the math in the db isn't viable. – Kris Sep 06 '12 at 15:22
4

Alternatively; do it in mysql before it goes into php instead:

SELECT DATE_ADD(`date_column`, INTERVAL 10 DAY);
Kris
  • 40,604
  • 9
  • 72
  • 101
  • I think processing it in PHP is better. What if you also need the original date column? Now you need to pass back additional column. What if you also need to calculate 5 days? Again another column.. – Kris Sep 06 '12 at 15:04
  • 1
    those are what ifs that aren't covered by the original question, usually (in my experience) when people ask these things it is because they are unaware that they can do it in the database. It will almost certainly be faster in mysql if, especially if you need to do it for many rows. but of course if the situation is such that it makes more sense to do it in php, go for it. – Kris Sep 06 '12 at 15:08
  • True, but chances are you do need the original date value. I guess its more that your answer says "Don't do it in php" and comes off sounding as it is a bad thing to do it in php, instead of as an alternative solution. – Kris Sep 06 '12 at 15:13
  • Doing math on a column does not prevent selecting the original however I agree that the wording I used may come off wrong so I modified the answer text changed to something hopefully more suitable. – Kris Sep 06 '12 at 15:21