Page 1 of 1
Manipulating Strings as Dates
Posted: Sun Aug 20, 2006 9:30 am
by Seb Spiers
Hi There,
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;
Code: Select all
<? echo ( $date_commencing + 6 ) ; ?>
The output is not 28/06/1983, it simply outputs "28". It uses the numbers before the first "/". I want to handle the date as a date.
Can anyone help?
Ta! :X
Re: Manipulating Strings as Dates
Posted: Sun Aug 20, 2006 9:55 am
by Oren
Seb Spiers wrote:It uses the numbers before the first "/".
Of course it is, it's a string
Edit: Have a read:
http://us2.php.net/manual/en/language.t ... ggling.php
Posted: Sun Aug 20, 2006 10:23 am
by blackbeard
Here's one way to do it:
Code: Select all
$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);
That should do it.
Posted: Sun Aug 20, 2006 10:47 am
by RobertGonzalez
strtotime() then add/substract seconds.
Posted: Sun Aug 20, 2006 10:58 am
by Oren
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).
Posted: Sun Aug 20, 2006 11:01 am
by RobertGonzalez
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.
Posted: Sun Aug 20, 2006 12:28 pm
by blackbeard
I didn't think about the day range. Could do this instead:
Code: Select all
$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.
Posted: Sun Aug 20, 2006 5:38 pm
by RobertGonzalez
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.