0

I am calculating age of a person as follows-

$dob = new DateTime('01-03-2004', new DateTimeZone("Asia/Dhaka"));
$to = new DateTime("28-02-2022", new DateTimeZone("Asia/Dhaka"));
$interval = $dob->diff($to);

It returns 17 years 11 months 29 days.

But calculator.net shows 17 years 11 months 27 days.

Is there any other technique to calculate age in php?

s.k.paul
  • 7,099
  • 28
  • 93
  • 168

1 Answers1

0

The difference is due to your time zone. Try using this:

$dob = new \DateTime('01-03-2004');
$to = new \DateTime("28-02-2022");
$interval = $dob->diff($to);

Without time zone specified, it will give you, your desired result.

Output:

DateInterval {#721 ▼
  interval: + 17y 11m 27d
  +"y": 17
  +"m": 11
  +"d": 27
  +"h": 0
  +"i": 0
  +"s": 0
  +"f": 0.0
  +"weekday": 0
  +"weekday_behavior": 0
  +"first_last_day_of": 0
  +"invert": 0
  +"days": 6573
  +"special_type": 0
  +"special_amount": 0
  +"have_weekday_relative": 0
  +"have_special_relative": 0
}
Saud
  • 859
  • 1
  • 9
  • 23
  • I am still not getting 27 days. – s.k.paul Jan 31 '22 at 07:41
  • @s.k.paul did you remove the time zone? – Saud Jan 31 '22 at 07:44
  • If you already removed the timezone from the object. There must be another instance or a global variable or property that is overriding the timezone in that object. You can use "UTC" as a parameter in the `DateTime()` object to override any predefined or default timezone. – Saud Jan 31 '22 at 08:01