Reputation: 49
I have this code, and it prints out as '01/01/1970'
$dob = mktime(0, 0, 0, date("m"), date("d")-1, date("y")-18);
echo "DOB is ".date("d/m/y", $dob);
Why is the year not 18 years less than today?
Upvotes: 1
Views: 124
Reputation: 777
The following code is imho much easier to read:
<?php
$dob = new DateTime();
printf("\nToday is %s", date_format($dob, 'D, M d Y'));
$dob->modify('-1 day');
$dob->modify('-18 year');
printf("\nToday minus %d day and %d year is %s",
-1, -18,
date_format($dob, 'D, M d Y'));
?>
Don't you agree? It is not so difficult to calculate date with PHP. Just look also at the PHP Date function for the various formats, such as Weeknumbers.
Upvotes: 0
Reputation: 33163
date("y") == 11
and 11-18 == -7
. You need date("Y") == 2011
.
Debugging tip: Print out separate parts of the code so you see what's going on. echo $dob
shows that the problem is on the first line, and echo date("y")-18
tells that it's the last argument to mktime()
that causes it.
Upvotes: 5
Reputation: 29166
According to the manual, when you specify small y
as the argument to date
function, it will return two-digit representation of the current year. Since the current year is 2011, it will return 11. Subtracting 18 from it will give you a negative result, that's why mktime
is resetting to the original timestamp.
Change date("y")
to date("Y")
, that is, replace small y
with capital Y
, then you will get the desired result.
Upvotes: 1
Reputation: 1701
This is the easiest solution :
$dob = strtotime('-18 years');
echo date('d/m/y', $dob);
strtotime()
is a powerful function.
Upvotes: 3
Reputation: 18588
try
$dob = mktime(0, 0, 0, date("m"), date("d")-1, date("Y")-18);
echo "DOB is ".date("d/m/y", $dob);
Upvotes: 2