Link to home
Start Free TrialLog in
Avatar of deanlee17
deanlee17

asked on

Subtracting PHP dates

Hi Experts,

I needed to subtract an arrival date from a departure date to work out the number of nights a customer stayed. So I used

$Arrival_Date = strtotime($Arrival_Date);
$Departure_Date = strtotime($Departure_Date);
$NoNights = ($Departure_Date - $Arrival_Date) / 86400;

This seemed to work fine, however I now need to put those 2 variables back into the correct format to be stored in my MySql table. How can I do this? and secondly a friend said I should be using MkDate to do this kind of thing, is this true?

Many Thanks,
Dean
Avatar of Guy Hengel [angelIII / a3]
Guy Hengel [angelIII / a3]
Flag of Luxembourg image

there, you actually use the date() function to return the string in format YYYY-MM-DD (and with time HH24:MI:SS)
http://php.net/manual/en/function.date.php
ASKER CERTIFIED SOLUTION
Avatar of Beverley Portlock
Beverley Portlock
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of deanlee17
deanlee17

ASKER

bportlock, thats superb, thanks very much for this.

I think he said the method above struggles on leap yours or something like that. So what occasions would you actualyl use mkdate over your preferred method of 'date' and 'strtotime'?

Thanks.
If I need to do calculations that are very precise I use Julian Dates http://uk3.php.net/manual/en/function.gregoriantojd.php but for 99% of my programming needs the leap year will make no difference. Most people accept vague terms like "Next Month" which can be virtually anything from 1st of next to the 31st.

strtotime is frighteningly flexible - look at these examples from http://www.php.net/strtotime

echo strtotime("now"), "\n";
echo strtotime("10 September 2000"), "\n";
echo strtotime("+1 day"), "\n";
echo strtotime("+1 week"), "\n";
echo strtotime("+1 week 2 days 4 hours 2 seconds"), "\n";
echo strtotime("next Thursday"), "\n";
echo strtotime("last Monday"), "\n";
Typos in the examples above corrected below

echo "<pre>\n";
echo strtotime("now") . "\n";
echo strtotime("10 September 2000") . "\n";
echo strtotime("+1 day") . "\n";
echo strtotime("+1 week") . "\n";
echo strtotime("+1 week 2 days 4 hours 2 seconds") . "\n";
echo strtotime("next Thursday") . "\n";
echo strtotime("last Monday") . "\n";
echo "</pre>\n";
Thats great, thanks very much :)