[JAVA] A formula that simply calculates the age from the date of birth

Formula and proof to simply calculate age from date of birth

a formula

When you want to easily find the age from your birthday From today's date in yyyymmdd format, the birthday also in yyyymmdd format can be subtracted as is, and the integer part of the solution divided by 10,000 can be used as the current age.

For example, if today is August 18, 2017 and your birthday is August 20, 1990,

\begin{align}
\mbox{age}
&=floor\left(\frac{20170818-19900820}{10000}\right)\\
&=floor\left(\frac{269998}{10000}\right)\\
&=floor\left(26.9998\right)\\
&=26
\end{align}

The generalization of this is the following formula.

\begin{align}
\mbox{age}
&=floor\left(\frac{\left(\mbox{Current year}\times10000+\mbox{Current month}\times100+\mbox{Current date}\right)-\left(\mbox{Year of birth}\times10000+\mbox{Birth month}\times100+\mbox{birthday}\right)\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ }{10000}\right)
\end{align}

Calculation example

If today is 08/18/2017 and your birthday is 08/20/1990

\begin{align}
\text{age}
&= floor\left(\frac{\left(2017\times1000+08\times100+18\right)-\left(1990\times1000+08\times100+20\right)}{10000}\right)\\
&= floor\left(\frac{20170818-19900820}{10000}\right)\\
&= floor\left(\frac{269998}{10000}\right)\\
&= floor\left(26.9998\right)\\
&= 26
\end{align}

If today is 2017/08/20 and your birthday is 1990/08/20

\begin{align}
\text{age}
&= floor\left(\frac{\left(2017\times1000+08\times100+20\right)-\left(1990\times1000+08\times100+20\right)}{10000}\right)\\
&=floor\left(\frac{20170820-19900820}{10000}\right)\\
&=floor\left(\frac{270000}{10000}\right)\\
&=floor\left(27\right)\\
&=27
\end{align}

I just want to do something like "correct the elapsed milliseconds from UNIX time ..." with the spinal reflex, but when I think calmly, I think this logic is a very natural idea.

(For those who are not convinced [** Explanation here **](#% E6% 95% B0% E5% BC% 8F% E3% 81% AE% E3% 82% 84% E3% 82% 84% E8% A9% B3% E3% 81% 97% E3% 81% 84% E8% A7% A3% E8% AA% AC))

However, the definition of the age calculation formula may change depending on the target of use (especially in legal relations), so this calculation formula cannot always be used as it is.

code

When using JavaScript

calcAge.js


/**
 *A function that returns the age from the birthday
 * @param {!string} birthdayStr -Enter your birthday in yyyymmdd format
 * @return {number}Calculated age
 **/
var calcAge = function(birthdayStr){
  if(isNaN(birthdayStr)||birthdayStr.length !== 8){
    return -1;
  }
  var d = new Date();
  var dStr = ''+d.getFullYear()+('0'+(d.getMonth()+1)).slice(-2)+('0'+d.getDate()).slice(-2);
  return Math.floor((parseInt(dStr)-parseInt(birthdayStr))/10000);
};

console.log(calcAge('19900820'));

For Python 3.X

calcAge.py


# -*- coding: utf-8 -*-
from datetime import datetime
import math

def calcAge(birthdayStr):
  if not (birthdayStr.isdigit() and len(birthdayStr)==8):
    return -1
  dStr = datetime.now().strftime("%Y%m%d")
  return math.floor((int(dStr)-int(birthdayStr))/10000)

print(calcAge("19900817"))

The expression for return is

python


return (int(dStr)-int(birthdayStr))//10000

But OK.


In Ruby

calcAge.rb


require "date"
def calcAge(birthdayStr)
  if birthdayStr !~ /^[0-9]{8}$/
    return -1
  end
  return (Date.today.strftime("%Y%m%d").to_i - birthdayStr.to_i) / 10000
end

print calcAge("19900820")

In Ruby, the fractional part is arbitrarily truncated when dividing between integer types, so floor processing is not required.


In SQL

SQL date function (age calculation) | dbSheetClient IT technology blog

For PHP, Java, Perl

Yutaka Sano's server administrator diary --Simple formula to calculate age from date of birth: ITpro


In Excel

There is DATEDIF () function So this formula is unnecessary, but it is an effective means when the original data is not date type when importing and processing CSV.

=FLOOR.MATH((TEXT(TODAY(),"yyyymmdd")-[Date of birth in yyyymmdd format])/10000)

image.png

[FLOOR.MATH () Function](https://support.office.com/ja-jp/article/FLOOR-MATH-%E9%96%A2%E6%95%B0-c302b599-fbdb-4177-ba19- 2c2b1249a2f5) cannot be used in old Excel. In that case, use INT function OK if you use it.

=INT((TEXT(TODAY(),"yyyymmdd")-[Date of birth in yyyymmdd format])/10000)

Ilustration-The moment you get older

This formula calculates ** the current age **, but does not calculate ** how old you will be today **. [Age Calculation Niseki Suru Law](https://ja.wikipedia.org/wiki/%E5%B9%B4%E9%BD%A2%E8%A8%88%E7%AE%97%E3%83% According to 8B% E9% 96% A2% E3% 82% B9% E3% 83% AB% E6% B3% 95% E5% BE% 8B), ** the timing of aging ** is not the day of the birthday. ** The moment the day before the birthday expires ** (= 24:00: 0 the day before). That is, a person who was ** born on April 1, 2000 ** was 5 years old at the beginning of March 31, 2006, but will be 6 years old ** by the end of March 31, 2006, * * April 1, 2006 will be celebrated at the age of 6 **.

By this definition, even people born on February 29, leap year, age one year each year.

About birthday and grade

According to the School Education Law, ** people who are 6 years old by the day before April 1 ** are required to enter elementary school. "People born on April 1, 2000" are ** 6 years old on March 31, 2006, the day before April 1, 2006 **, so ** April 1, 2006 Became a first grader ** from the day. For the same reason, "people born on March 15, 2000" and "people born on April 20, 1999" are in the same grade.

"People born on April 2, 2000" have not reached the age of 6 the day before April 1, 2006, so they will be in the first grade of elementary school from April 1, 2007, the following year.


A slightly detailed explanation of mathematical formulas

For those who want to dig a little deeper. Even information on the year of birth and the current year can tell you how old you will be this year.

This year's age = current year-year of birth

However, I don't know "current age" because I don't know if I've reached this year's birthday. If ** is not celebrating this year's birthday **, then ** "current age" must be calculated ** by subtracting $ 1 $ from "this year's age".

This can be expressed by the ** case-specific formula ** as follows.

\begin{eqnarray}
\mbox{age}=\left\{
\begin{array}{ll}
\mbox{Current year}-\mbox{Year of birth}&\left(\mbox{Birth date}\leq\mbox{Current date}\right)\cdots\mbox{(1)Ceremony after this year's birthday}\\
\mbox{Current year}-\mbox{Year of birth}\color{red}{-1}&\left(\mbox{Birth date}>\mbox{Current date}\right)\cdots\mbox{(2)Ceremony until the day before this year's birthday}\\
\end{array}
\right.
\end{eqnarray}

By transforming the simple formula for age, a formula similar to the above ** case-specific formula ** can be created. The $ \ color {red} {red character part} $ of this transformed formula contains the process of "$ -1 $ if this year's birthday is not reached".

\begin{align}
\mbox{age}
&=floor\left(\frac{\left(\mbox{Current year}\times10000+\mbox{Current month}\times100+\mbox{Current date}\right)-\left(\mbox{Year of birth}\times10000+\mbox{Birth month}\times100+\mbox{birthday}\right)\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ }{10000}\right)\\
&=floor\left(\frac{\left(\mbox{Current year}-\mbox{Year of birth}\right)\times10000+\left(\mbox{Current month}-\mbox{Birth month}\right)\times100+\mbox{Current date}-\mbox{birthday}\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ }{10000} \right)\\
&=\color{red}{floor}\left(\mbox{Current year}-\mbox{Year of birth}\color{red}{+\frac{\mbox{Current month}-\mbox{Birth month}}{100}+\frac{\mbox{Current date}-\mbox{birthday}}{10000}}\right)\\
\end{align}

Replacing the ** total portion of the calculation results for the month and day ** of this formula with $ X $ results in a simple formula that is very similar to the ** case-specific formula ** that appeared earlier.

\begin{align}
\mbox{age}&=\color{red}{floor}\left(\mbox{Current year}-\mbox{Year of birth}\color{red}{+X}\right)\\\\
\color{red}{X}&=\frac{\mbox{Current month}-\mbox{Birth month}}{100}+\frac{\mbox{Current date}-\mbox{birthday}}{10000}\\\\\\
\end{align}

The range that the value of $ X $ can take is as follows

--When today is the day of your birthday

→ Current month = birth month, current date = birthday, so $ 0 $

--When today is December 31st and your birthday is January 1st

→ Maximum value $ X_ {max} $

\begin{align}
X_{max}&=\frac{\mbox{12}-\mbox{1}}{100}+\frac{\mbox{31}-\mbox{1}}{10000}=0.1130\\\\
\end{align}

--When today is January 1st and your birthday is December 31st

→ Minimum value $ X_ {min} $

\begin{align}
X_{min}&=\frac{\mbox{1}-\mbox{12}}{100}+\frac{\mbox{1}-\mbox{31}}{10000}=-0.1130
\end{align}

Therefore

-0.1130\leq X \leq 0.1130
Relationship between present and birthday within the year XPossible value of
\mbox{Birth date}\leq\mbox{Current date}At (after birthday) 0\leq X_{after}\leq0.1130
\mbox{Birth date}>\mbox{Current date}At (before the day before the birthday) -0.1130\leq X_{before}<0

Calculation after the day of this year's birthday

The result of "$ \ mbox {current year}-\ mbox {birth year} $" is always an integer greater than or equal to $ 0 $, which is $ 0 \ leq X_ {after} \ leq 0.1130 $. $ X $ does not affect the calculation result and is ignored.

\begin{align}
\mbox{age}
&=floor\left(\mbox{Current year}-\mbox{Year of birth}\color{red}{+X_{after}}\right)\\
&=\mbox{Current year}-\mbox{Year of birth}
\end{align}

This is consistent with the ** case-specific formula "(1) Formula after this year's birthday" **.

Calculation when the birthday of the year has not yet arrived

The result of "$ \ mbox {current year}-\ mbox {birth year} $" is always an integer greater than or equal to $ 0 $, which is $ -0.1130 \ leq X_ {before} <0 $. $ X $ has the effect of subtracting 1 from the calculation result for the year.

\begin{align}
\mbox{age}
&=floor\left(\mbox{Current year}-\mbox{Year of birth}\color{red}{+X_{before}}\right)\\
&=\mbox{Current year}-\mbox{Year of birth}\color{red}{-1}
\end{align}

This is consistent with the ** case-specific formula "(2) formula until the day before this year's birthday" **.

Therefore, the formula

\begin{align}
\mbox{age}
&=floor\left(\frac{\left(\mbox{Current year}\times10000+\mbox{Current month}\times100+\mbox{Current date}\right)-\left(\mbox{Year of birth}\times10000+\mbox{Birth month}\times100+\mbox{birthday}\right)\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ }{10000}\right)
\end{align}

The solution of is the same as the following formula, and the current age can be calculated from the birthday.

\begin{eqnarray}
\mbox{age}=\left\{
\begin{array}{ll}
\mbox{Current year}-\mbox{Year of birth}&\left(\mbox{Birth date}\leq\mbox{Current date}\right)\cdots\mbox{(1)Ceremony after this year's birthday}\\
\mbox{Current year}-\mbox{Year of birth}\color{red}{-1}&\left(\mbox{Birth date}>\mbox{Current date}\right)\cdots\mbox{(2)Ceremony until the day before this year's birthday}\\
\end{array}
\right.
\end{eqnarray}

Afterword

One of the interesting things about programming is how to make the processing in the brain ** concrete and put it into simple logic **. This code is simply packed with fun, so it was fun just looking at it.

If you are interested in Excel date processing, please also check here. → [Excel] Identity of date and time information --Qiita

For those who want to do more solid inspection of yyyymmdd format → Reading the regular expression that checks the validity of the date string in yyyymmdd format --Qiita

Reference link

-"Simple formula to calculate age from date of birth" is not always available --Nayami, a local government employee in charge of computerization -When do people get older after all: the best days for reading naname ―― Legal office column ―― Is the child born on April 1 born early? : House of Councilors Legal Affairs Bureau -About the grades of children born on April 1: Ministry of Education, Culture, Sports, Science and Technology -Age: Wikipedia

Recommended Posts

A formula that simply calculates the age from the date of birth
[Python] Get the update date of a news article from HTML
I made a Line bot that guesses the gender and age of a person from an image
[Python] A program that calculates the number of chocolate segments that meet the conditions
From a book that makes the programmer's way of thinking interesting (Python)
[Python] A program that calculates the number of updates of the highest and lowest records
The story of launching a Minecraft server from Discord
[Python] A program that counts the number of valleys
Calculate volume from the two-dimensional structure of a compound
A python script that gets the number of jobs for a specified condition from indeed.com
Make a BOT that shortens the URL of Discord
Python points from the perspective of a C programmer
A programming language that protects the people from NHK
# Function that returns the character code of a string
I want a Slack bot that calculates and tells me the salary of a part-time job from the schedule of Google Calendar!
Generate that shape of the bottom of a PET bottle
A story that analyzed the delivery of Nico Nama.
[Python] A program that compares the positions of kangaroos.
A library that monitors the life and death of other machines by pinging from Python
An example of a mechanism that returns a prediction by HTTP from the result of machine learning
A Python script that allows you to check the status of the server from your browser
A tool that automatically turns the gacha of a social game
A program that removes specific characters from the entered text
Different from the import type of python. from A import B meaning
The story of a Django model field disappearing from a class
Iterator that can scan forward from the middle of the sequence
Create a correlation diagram from the conversation history of twitter
A Python script that compares the contents of two directories
A memo that reproduces the slide show (gadget) of Windows 7 on Windows 10.
When incrementing the value of a key that does not exist
pandas Fetch the name of a column that contains a specific character
Shell script (Linux, macOS) that outputs the date of the last week
A story that struggled to handle the Python package of PocketSphinx
From a book that programmers can learn (Python): Find the mode
From a book that programmers can learn ... (Python): Review of arrays
A function that measures the processing time of a method in python
The story of creating a site that lists the release dates of books
I made a slack bot that notifies me of the temperature
I made a program that automatically calculates the zodiac with tkinter
[python] A note that started to understand the behavior of matplotlib.pyplot
The story of making a module that skips mail with python
[Python] A program that rotates the contents of the list to the left
Best 3 from the impressions of reading a new shell programming textbook
A story about creating a program that will increase the number of Instagram followers from 0 to 700 in a week
Existence from the viewpoint of Python
The story of writing a program
A story that visualizes the present of Qiita with Qiita API + Elasticsearch + Kibana
Extract lines that match the conditions from a text file with python
A program that will slowly recover the economy from any news headline
I wrote a corpus reader that reads the results of MeCab analysis
The story of developing a web application that automatically generates catchphrases [MeCab]
How to create a wrapper that preserves the signature of the function to wrap
I made a simple timer that can be started from the terminal
The eval () function that calculates a string as an expression in python
A note about the functions of the Linux standard library that handles time
The story of making a package that speeds up the operation of Juman (Juman ++) & KNP
Find out the name of the method that called it from the method that is python
Get the average salary of a job with specified conditions from indeed.com
[Python] Note: A self-made function that finds the area of the normal distribution
A simple mock server that simply embeds the HTTP request header in the body of the response and returns it.
I created a Slack bot that confirms and notifies AWS Lambda of the expiration date of an SSL certificate