Note that there are some explanatory texts on larger screens.

plurals
  1. POAdding months to a date with keeping the last day of given month
    primarykey
    data
    text
    <p>Suppose that I have a date <strong>"Jan 31 2011"</strong> and I want to add a <strong>month</strong> to this date.</p> <p>New date is is okay <strong>"Feb 28 2011"</strong>, when I want to add a month again it gives me <strong>"March 28 2011"</strong>, but I need it to be <strong>"March 31 2011"</strong>. </p> <p>Oracle has a built-in function for that as Tony Andrews replied to this question,<br> <a href="https://stackoverflow.com/questions/397631/add-date-without-exceeding-a-month">Add date without exceeding a month</a></p> <p>But how to implement this function in PHP? (also MySQL solution is welcome)</p> <p><strong>edit #1</strong><br> @zerkms, this is the nearest answer thanks for your help. Here is the second deal</p> <p>I changed your solution a little bit to solve my real-life problem</p> <pre><code>SET @BEGINNING_DATE := '2011-01-30'; /* first date for payment */ SET @NEXT_END_DATE := '2011-02-28'; /* next date for payment (second payment deadline) */ /* now I want to find third payment deadline */ SELECT IF(@BEGINNING_DATE = LAST_DAY(@BEGINNING_DATE), LAST_DAY(DATE_ADD(@NEXT_END_DATE, INTERVAL 1 MONTH)), DATE_ADD(@NEXT_END_DATE, INTERVAL 1 MONTH)) </code></pre> <p>Your helpful solution gives me "2011-03-28" but I want to "2011-03-30". Any ideas?</p> <p><strong>edit #2</strong><br> Here is the solution with @zerkms' help. Thank you!</p> <pre><code>SET @BEGINNING_DATE := '2011-02-28'; /* first date for payment */ SET @NEXT_END_DATE := '2011-05-31'; /* next date for payment (second payment deadline */ SELECT IF(@BEGINNING_DATE = LAST_DAY(@BEGINNING_DATE), LAST_DAY(DATE_ADD(@NEXT_END_DATE, INTERVAL 1 MONTH)), CONCAT(YEAR(DATE_ADD(@NEXT_END_DATE, INTERVAL 1 MONTH)),'-',LPAD(MONTH(DATE_ADD(@NEXT_END_DATE, INTERVAL 1 MONTH)),2,'0'),'-',DAY(@BEGINNING_DATE))) </code></pre> <p><strong>edit #3</strong> Here is the exact solution. After dealing with some strange behaviours this is the exact solution</p> <pre><code>SET @@session.sql_mode = 'ALLOW_INVALID_DATES'; SET @BEGINNING_DATE := '2011-01-29'; /* first date for payment */ SET @NEXT_END_DATE := '2011-02-28'; /* next date for payment (second payment deadline) */ SELECT IF(@BEGINNING_DATE = LAST_DAY(@BEGINNING_DATE), LAST_DAY(DATE_ADD(@NEXT_END_DATE, INTERVAL 1 MONTH)), CONCAT(YEAR(DATE_ADD(@NEXT_END_DATE, INTERVAL 1 MONTH)),'-',MONTH(DATE_ADD(@NEXT_END_DATE, INTERVAL 1 MONTH)),'-',DAY(@BEGINNING_DATE)) + INTERVAL 0 MONTH) </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload