How do I add months to today's date in php and mysql?

lyderslim

New member
I need to insert today's date and today's date + 3 months into two DATE fields in my mysql database.

I'm assuming that I use the CURDATE() function to get today's date. How do I add 3 months to that and insert it into my database?

And what is the best reference for this type of stuff? I can't understand php.net for some reason.
 
The best way to work the dates for inserting (or even building up a select query with MySQL) is using PHP to create the values.

Just as an example:

<?php
$currentDate = date('m/d/Y');
?>

To get the date from 3 months after the current date you will need some math, so..

<?php
$day = date('d');
$month = date('m');
$year = date('Y');

$endMonth = $month + 3;

switch($endMonth) {
case 1:
$year++;
break;
case 2:
{
if ($day > 28)
{
// check if the year is leap
$day = 28; // or you can keep the day and increase the month
}
}
break;
default:
// nothing to do
break;
}

$endMkTime = mktime(0,0,0,$endMonth,$day,$year);
$endDate = date('m/d/Y',strtotime($endMkTime));
?>

The CURDATE should be used in default values on the mysql tables. If you have a field that needs the current date upon creation, this default value should work very well for you.
 
Back
Top