05-19-2018, 09:20 PM
Hello everybody, so iam going to show you how to calculate your Age with full detailes (Y/M/H/m/s/ms/ns/ms) in PHP by Date of Birth.
If you Wanna Calculate your real Age in numeric format:
You Have to subtract date('year') from date('Y') and insert on the last date function's timestamp argument strtotime('Year-Month-Day')
Output:
If you Wanna Calculate your real age with full details (Y/M/H/m/s/ms/ns/ms):
1- We initializate the $datebirth var with the DateTime Class and set the timestamp argument of the DateTime Class to your Date of Birth with the following Syntax Year-Month-Day
2- We initializate the $today var with the DateTime Class without setting any arguments to get Today's Timestamp
3- We do the algorithm to calculate the requested Person's Age with DateTime::diff and then to get the result we must use DateInterval::Format
Let's Discuss somethings in our small algorithm...
Output:
Download Full Example Code: https://gist.github.com/JohnMagdy/8f8411...31cb9ec602
If you Wanna Calculate your real Age in numeric format:
You Have to subtract date('year') from date('Y') and insert on the last date function's timestamp argument strtotime('Year-Month-Day')
PHP Code: (Select All)
To Be: date("Y") - date("Y", strtotime('Year-Month-Day'))
For Example: date("Y") - date("Y", strtotime('2002-09-16')))
Code: (Select All)
16
If you Wanna Calculate your real age with full details (Y/M/H/m/s/ms/ns/ms):
1- We initializate the $datebirth var with the DateTime Class and set the timestamp argument of the DateTime Class to your Date of Birth with the following Syntax Year-Month-Day
PHP Code: (Select All)
To Be: $datebirth = new DateTime('Year-Month-Day');
For Example: $datebirth = new DateTime('2002-09-16');
PHP Code: (Select All)
To Be: $today = new DateTime;
PHP Code: (Select All)
For Example: echo $today->diff($dabi)->format('%y Years, %m Months, %d Days, %h Hours, %I Minutes, %s Seconds, ' . ($today->diff($dabi)->format('%s')*1000) . ' Milliseconds, ' . ($today->diff($dabi)->format('%s')*1000*1000000) . ' Nanoseconds, ' . ($today->diff($dabi)->format('%s')*1000*1000000*1000) . ' Microseconds');
Let's Discuss somethings in our small algorithm...
- We multiply the seconds in one thousand to get the Milliseconds.(Second = 1000 Milliseconds)
- We multiply the milliseconds in one thousand ms and the result get multiplied in one million ms to get the Nanosecond.(Nanosecond = 1000000 Millisecond)
- We multiply the Microseconds in one thousand ms and the result get multiplied in one million ms and the second result get multiplied in one thousand, to get the Microsecond.(Microsecond = 1000 Nanosecond)
Output:
Code: (Select All)
15 Years, 8 Months, 3 Days, 19 Hours, 25 Minutes, 45 Seconds, 45000 Milliseconds, 45000000000 Nanoseconds, 45000000000000 Microseconds
Download Full Example Code: https://gist.github.com/JohnMagdy/8f8411...31cb9ec602