1

I need to calculate age in php. I use this solution:

$birthdate = '1986-09-16';

$_age = floor( (strtotime(date('Y-m-d')) - strtotime($birthDate)) / 31556926);

from here

Everything works fine, but for example if

$birthday = '1194-01-06' or

$birthday = '1900-01-01'

result is always 44.

if $birthday = '1910-11-09' everything is fine again and result is 103. Why?

Note: I don't want to use diff() function, because of some issues.

EDIT:

Earlier i had problems with diff(), some

Warning range()

showed during processing and after refreshing of website everything was fine again... i could not find solution to fix it and somewhere i read that using of diff() could cause it. So i tried other solution and it worked... until now.

Finally I used this solution:

$birthDate = from database in timestamp format...
$birth = new \DateTime($birthDate);
$now = new \DateTime;
$age = $now->diff($birth)->y;

and I randomly get

Warning 
range(): step exceeds the specified range

again.

Community
  • 1
  • 1
  • [XY Problem](http://meta.stackexchange.com/a/66378). What are these 'issues' with `DateTime::diff()`? – Sammitch Apr 24 '14 at 21:32
  • 1
    Also `strtotime(date('Y-m-d'))` is a horrendously roundabout way to get `time()`. – Sammitch Apr 24 '14 at 21:34
  • 1
    Not sure what's going on but you better try this http://stackoverflow.com/questions/676824/how-to-calculate-the-difference-between-two-dates-using-php – user2387149 Apr 24 '14 at 21:35

3 Answers3

1

It's because you're using date that is using timestamp that has a default value of time() that is based on EPOCH that started on January 1 1970 00:00:00 GMT - it's 44 years since 1970.

More on this can be found in the PHP Manual: http://php.net/manual/en/function.date.php

benomatis
  • 5,536
  • 7
  • 36
  • 59
0

Have you read strtotime() manual (https://php.net/manual/en/function.strtotime.php)?

The function expects to be given a string containing an English date format and will try to parse that format into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 UTC), relative to the timestamp given in now, or the current time if now is not supplied.

DarkSide
  • 3,670
  • 1
  • 26
  • 34
0

Integer limit issue, either:

  1. Your OS doesn't handle negative timestamps
  2. The maximum integer values for signed integers on a 32 bit system

strtotime()

The valid range of a timestamp is typically from Fri, 13 Dec 1901 20:45:54 UTC to Tue, 19 Jan 2038 03:14:07 UTC. (These are the dates that correspond to the minimum and maximum values for a 32-bit signed integer.)

Additionally, not all platforms support negative timestamps, therefore your date range may be limited to no earlier than the Unix epoch (1 Jan 1970).

AbraCadaver
  • 78,200
  • 7
  • 66
  • 87