Marty
Marty

Reputation: 49

PHP Date not calculating properly

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

Answers (5)

Harm
Harm

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

JJJ
JJJ

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

MD Sayem Ahmed
MD Sayem Ahmed

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

Tom
Tom

Reputation: 1701

This is the easiest solution :

$dob = strtotime('-18 years');
echo date('d/m/y', $dob);

strtotime() is a powerful function.

Upvotes: 3

robjmills
robjmills

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

Related Questions