Convert age to current date

Is there any PHP function to convert the current age to date in the YYYY-MM-DD format. I saved the DOB in the format YYYY-MM-DD , and I want to run the SQLite query:

 SELECT FirstName FROM mytable WHERE DOB >= $MinAge AND DOB <= '$MaxAge'; 

I searched google to convert date format to date, but could not find any function, is there anyone who can help?

+4
source share
1 answer

Is there any PHP function to convert the current age to date

No, age contains less information than date. There are 365 possibilities for a person over the age of X, but the date of birth of the card is exactly one age.

In other words, if I tell you that I am 20, and ask you to tell me my birthday, you cannot say for sure. However, if I tell you my birthday, you can confidently tell me my age.

Since your column is called DOB, I assumed that you saved the date of birth, not age. In this situation, you can get users who fall into a certain age range.


Suppose you want to find all users between the ages of 18 and 50 (including 18 and 50).

For a user who is 18 years old today, his birthday should be:

  • before or after today - 18 years
  • after today - 19 years

For a user who will be 50 today, his birthday should be:

  • before or after today - 50 years
  • after today - 51 years

Note that the "before or after" and "after" are simply "<=" and ">" respectively.

So, what if you want all users between the ages of 18 to 50?

You can just take two outer borders:

User age is from 18 to 50 iff:
dob <= (today -18 years) and dob > (today - 51 years)

 $lower = date('Ym-d', strtotime('today -18 years')); $upper = date('Ym-d', strtotime('today -51 years')); $query = "SELECT FirstName FROM users WHERE dob >= '$lower' AND dob < '$upper';"; 

Note that if you plan dates before 1970 (52-es), you most likely should use DateTime instead of date and sttrtotime (I actually use DateTime in the actual code, but date / strtotime do for shorter examples).

Example 85 years ago with DateTime:

 $d = new DateTime('today -85 years'); $s = $d->format('Ym-d'); //1927-06-03 as of 3 June 2012 
+5
source

Source: https://habr.com/ru/post/1415792/


All Articles