PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!
Ive got a simple html form with a text field in which a date is entered in a dd/mm/yyyy format.
I want to be able to manipulte the date by adding and subtracting days.
The problem i've found is that if I enter 22/06/1983 and for example do;
$dummy = explode("/", $date_commencing) // Have to break up the string, it's not in US format
/* $dummy[0] will be the day of the month
$dummy[1] will be the month
$dummy[2] will be the year
*/
$newTime = mktime (0, 0, 0, $dummy[1], $dummy[0]+6, $dummy[2]); // added 6 days to the timestamp
$newDate = date ("m/d/Y", $newTime);
Listen to Everah, the other suggested method will fail when the day of the month is 28 for example.
Note that Everah's method also has some limitations:
1. Make sure the date you pass to strtotime() is in the form of: mm/dd/yyyy and not dd/mm/yyyy
2. It will fail with very old dates such as 1/1/1800 (just an example) and also with dates such as 1/1/2100 (again, just an example).
Thanks for point that out Oren. Yes, I believe strtotime() is bound by the limits of the unixtimestamp and the handling of large numbers by your processor. For common dates after 1970 (positive integers) and before 2038 (also positive integers) you should be OK.
$dummy = explode("/", $date_commencing) // Have to break up the string, it's not in US format
/* $dummy[0] will be the day of the month
$dummy[1] will be the month
$dummy[2] will be the year
*/
$newTime = mktime (0, 0, 0, $dummy[1], $dummy[0], $dummy[2]) + (60*60*24*6);
// 60 seconds * 60 minutes * 24 hours * 6 days)
$newDate = date ("m/d/Y", $newTime);
Since we have to break up the date string anyways, I figured going right to mktime would be faster than putting the date string back together and then calling strtotime.
strtotime() is designed to take just about any readable formatted date. Read the manual on it. Of course, you can still do things the way you want to, but keep in mind that strtotime() is designed for different date formats.