1

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?

4
  • Try it on writecodeonline.com/php (It gives 15/09/03. As if you used "Y". Weird. Ideone and codepad give 01/01/70.) Commented Sep 16, 2011 at 8:09
  • @Ray Toal: or codepad.org Commented Sep 16, 2011 at 8:13
  • @Sayem Edited the comment. I was pointing out writecodeonline for some reason is treating y as Y. I don't know why! Commented Sep 16, 2011 at 8:14
  • @Ray Toal: Yup, you are right.That's weird......... Commented Sep 16, 2011 at 8:16

5 Answers 5

5

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.

Sign up to request clarification or add additional context in comments.

Comments

3

This is the easiest solution :

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

strtotime() is a powerful function.

Comments

2

try

$dob = mktime(0, 0, 0, date("m"), date("d")-1, date("Y")-18);
echo "DOB is ".date("d/m/y", $dob); 

Comments

1

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.