Reputation: 59
I use now()
function to obtain a date. I tried to add a month with many functions like:
$today= date("Y-m-d");
$date1 = date('Y-m-d', strtotime($today, ' + 1 month'));
and after load $date1
to MySQL DB, but when I see in DB the date inserted is 0000-00-00
.
How can I add this month?
Upvotes: 1
Views: 897
Reputation: 3758
Having a date in MySQL turn up as 0000-00-00 00:00:00
usually indicates that the date you tried to store in the database did not have a valid format / was not recognized as date by MySQL. Maybe it is a problem with the way you insert or update the date value?
You can also directly add a month to a date in MySQL without the need to do the calculation in PHP by using the builtin function DATE_ADD() of MySQL:
SELECT DATE_ADD(NOW(), INTERVAL 1 MONTH);
For example, the query
SELECT DATE_ADD('2018-05-15 12:34:56', INTERVAL 1 MONTH);
will return the result:
+---------------------------------------------------+
| DATE_ADD('2018-05-15 12:34:56', INTERVAL 1 MONTH) |
+---------------------------------------------------+
| 2018-06-15 12:34:56 |
+---------------------------------------------------+
1 row in set (0.00 sec)
Using that you could also directly update a date value to a date that is one month ahead:
UPDATE table_name SET column_name = DATE_ADD(NOW(), INTERVAL 1 MONTH)
WHERE id = your_id;
(Replace table_name, column_name, id and your_id according to your needs.)
Upvotes: 0
Reputation: 219924
You made this more complicated than it needs to be.
$date1 = date('Y-m-d', strtotime(' + 1 month'));
strtotime()
will assume "now" if you do not pass it a date and time.
Otherwise, the way you called it, you should be seeing this error:
Warning: strtotime() expects parameter 2 to be integer, string given in /tmp/execpad-a8173d5d91cb/source-a8173d5d91cb on line
This is because strtotime()
expects the second parameter to be a Unix timestamp and you clearly provide a string. The closet approximation to your code would be
$today= time();
$date1 = date('Y-m-d', strtotime(' + 1 month', $today));
If the date is still going into the database incorrectly then you have an issue outside of your date code.
Upvotes: 1