This may sound like a dumb question, but how can I convert the time between two dates to a percent?
I am using this Jquery plugin: http://tinacious.github.io/goalProgress/
The script on page that calculates the percent is:
$('#timerGoal').goalProgress({
goalAmount: 100,
currentAmount: 40,
textBefore: '',
textAfter: '% Completed.'
});
Where it says goalAmount: I'd like that to remain at 100, but where it says currentAmount: 40, I'd somehow like to find the difference in percentage between two days, I know I'd have to set a start date, current date, and end date to find a percentage.
I'm certain part of the code would have to be:
$startDate = '01/01/2015 12:00:00';
$currentDate = date('d/M/Y H:i:s');
$endDate = '02/15/2015 12:00:00';
Finding the difference in two dates is fairly easy, but it's the third date thing I cannot grasp, especially to make it a percentage.
Any ideas?
I was thinking something along the lines of:
[Taken from: How to find the difference in days between two dates ]
$daylen = 60*60*24;
$date1 = '2010-03-29';
$date2 = '2009-07-16';
echo (strtotime($date1)-strtotime($date2))/$daylen;
But everything I read on is two dates not three.
Here is what I've come up with.
It's not calculating percentages yet, but it's something to possibly go off of:
$startDate = '08/01/2015 12:00:00';
$currentDate = date('d/M/Y H:i:s');
$endDate = '09/01/2015 12:00:00';
$startDate =str_replace(array(':', '/', ' '), '', $startDate);
$currentDate =str_replace(array(':', '/', ' '), '', $currentDate);
$endDate =str_replace(array(':', '/', ''), ' ', $endDate);
$mainPercent = $endDate - $startDate;
$actualPercent = $endDate - $currentDate;
$displayPercent = $actualPercent/$mainPercent * 100;
echo $displayPercent;
With todays date being 08/07/2015 I am getting 901.2015119993 which is obviously not a percent, but it's a start.
Working Solution:
$startDate = strtotime('08/01/2015 12:00:00');
$currentDate = time(date('d/M/Y H:i:s'));
$endDate = strtotime('09/15/2015 12:00:00');
$dateDivideBy = $endDate - $startDate;
$dateDivide = $currentDate - $startDate;
$divideProduct = $dateDivide / $dateDivideBy;
$datePercent = round($divideProduct * 100);
echo $datePercent;
With this working code and todays date being 08/07/2015 the value of $datePercent is 14.
The difference between two times, by itself, really can't be converted to a percentage. It's just a period of time. In order to figure out what percentage is complete, you would need to know how long the entire goal is supposed to take (an estimated time, I assume.) Then you can figure out the percentage like this:
ElapsedTime / TotalTime * 100
The total time would be End Date - Start Date, and the elapsed time would be now - start date.
Rather than using string functions to manipulate the dates, it would be better to use DateTime functions.
$startDate = '08/01/2015 12:00:00';
$endDate = '09/01/2015 12:00:00';
$startDate = new DateTime($startDate);
$currentDate = new DateTime(); // defaults to now
$endDate = new DateTime($endDate);
$totalTime = $endDate->diff($startDate)->format('%a');
$elapsedTime = $currentDate->diff($startDate)->format('%a');
// diff returns a DateInterval object; calling its format method
// with %a returns the number of days in the interval
$percent = ($elapsedTime / $totalTime) * 100;
I believe this is your desired outcome, where result is the resulting percent difference between start_actual_time and percent_time:
var percent_time= new Date("01/17/2013 11:20");
var start_actual_time = new Date("01/17/2012 11:20");
var end_actual_time = new Date("01/17/2014 11:20");
var range = end_actual_time - start_actual_time;
var diff = end_actual_time - percent_time;
var result = (diff / range)*100;
In this example, start_actual_time and percent_time are 40% different.
I've been trying to figure out how to output the amount of weeks between 2 dates using strings given to my server.
Every thread I found that has potentially the same problem as me is using datetime() which I'm not extremely familiar with, and I believe uses a different structure than me.
Anyways, I can't figure this out and I've been trying for a couple of hours.
These are the strings I need to feed into the function:
From: "8/3/2015" to: "07/27/2015"
Note, the from string will change each week according to the monday from every week. Also, there are several To dates, and there will be a new one each week.
It would also be a lovely feature if it converted to months and years if it applies.
UPDATE
This is what I came up with, with the help of phplovers answer. This should successfully give you back the amount of days, unless its more than 7, then it would give you weeks, then months, then years.
Pardon the messiness.
$from = date_create($startDate);
$to = date_create($endDate);
$interval = date_diff($from, $to);
if( $interval->format("%a") % 7 == 0 ){
$amt = ($interval->format("%a") / 7);
if($amt == 1) {
$display = $amt . " Week";
} else {
if($amt >= 4) {
$amt2 = $interval->format("%m");
if($amt2 == 1) {
$display = $amt2 . " Month";
} else {
$display = $amt2 . " Months";
$amt3 = $interval->format("%y");
if($amt3 == 1) {
$display = $amt3 . " Year";
} else {
$display = $amt3 . " Years";
}
}
} else {
$display = $amt . " Weeks";
}
}
} else {
$display = ($interval->format("%a")) . " Days";
}
You'd just echo $display anywhere you needed the time difference.
I have used this in some earlier project. Hope this might help you.
function datediffInWeeks($date1, $date2)
{
if($date1 > $date2) return datediffInWeeks($date2, $date1);
$first = DateTime::createFromFormat('d/m/Y', $date1);
$second = DateTime::createFromFormat('d/m/Y', $date2);
return floor($first->diff($second)->days/7);
}
var_dump(datediffInWeeks('8/3/2015', '7/27/2015'));
First thing you need to do is convert the strings to something that is easy to work with. Unixtime is probably the easiest when you are doing comparisons. Unixtime is the number of seconds since the Unix Epoch (January 1, 1970). Here is what I would do:
$date_from = strtotime( '8/3/2015' ) // Change to your input
$date_to = strtotime( '07/27/2015' ) // Change to your input
$difference = $date_to - $date_from; // The seconds between these times
$seconds_in_minute = 60;
$seconds_in_hour = $seconds_in_minute * 60;
$seconds_in_day = $seconds_in_hour * 24;
$seconds_in_week = $seconds_in_day * 7;
$seconds_in_month = $seconds_in_day * 30;
$seconds_in_year = $seconds_in_day * 365;
Each of these variables store how many seconds are in the specific timeframe. What you can do is check agains these variables using some basic math.
$years = floor( $difference / $seconds_in_year );
$months = floor( ($difference - $years * $seconds_in_year ) / ( $seconds_in_month ) );
$days = floor( ( $difference - $years * $seconds_in_year - $months * $seconds_in_month ) / ( $seconds_in_day ) );
This is a long form example of what is happening in the date_diff() function in PHP. However, that function is only available post PHP 5.3, so if you are using an older version of PHP you can try this method.
As MrT stated, using date() functions you can achieve this easily:
$from = date_create("07/27/2015");
$to = date_create("08/03/2015");
$interval = date_diff($from, $to);
echo $interval->format("%a"); // %a will give difference in days
For more about formatting this take a look at date_diff()
Visit: http://php.net/manual/en/datetime.diff.php
$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('2009-10-13');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days');
There is an awesome PHP extension for this thing.Its called carbon.
Specifically, for your given task you can do the following(I am skipping the code of importing and stuff):
$dt = Carbon::create(2014, 1, 1);
$dt2 = Carbon::create(2014, 12, 31);
echo $dt->diffInWeeks($dt2);
The above function will give you your answer.
Also, you can use their createFromFormat() method to create carbon objects of date
Link:
http://carbon.nesbot.com/
The 'W' date format fetches the week of the year that the date falls in.
$from = date('W', strtotime('07/27/2015') ) ;
$to = date('W', strtotime('8/3/2015') ) ;
//$from and $to now have the week of the year that their dates fall in.
//This simple math produces the the number of weeks from one date to the next.
$numOfWeeks = $to - $from;
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
PHP:find day difference between two date(“YmdHis”) reture
I have two dates
$departure_Dtae=2012-07-25T07:30:00
$arrival_date =2012-07-25T10:25:00
T means Time i.e. in 2012-07-25T10:25:00 date is 2012-07-25 and the time is 10:25:00 (hr: mts: s)
I need to find out the total hrs between these two times
I.e. in this case the total hour is 2 hr and 55 minutes
But I don't know how I calculate this in PHP
Does anyone know this?
If using PHP Version 5.3+ then you can use DateTime::diff():
<?php
function getDiff($strStart, $strEnd) {
$start = DateTime::createFromFormat("Y-m-d G:i:s", $strStart);
$end = DateTime::createFromFormat("Y-m-d G:i:s", $strEnd);
return $start->diff($end)->format('%hhrs %imins and %sseconds ');
}
var_dump(getDiff('2012-07-25 07:30:00', '2012-07-25 10:25:00'));
its simple
$departure_Dtae="2012-07-25T07:30:00";
$arrival_date ="2012-07-25T10:25:00";
$departure_Dtae= str_replace("T", " ", $departure_Dtae);
$arrival_date= str_replace("T", " ", $arrival_date);
$diff= (strtotime($arrival_date)-strtotime($departure_Dtae));
echo date("h",$diff);
Try this :
$end_time = "2008-09-05 20:59:13";
$start_time = "2008-09-05 19:00:16";
$end = date("h:i:s",strtotime($end_time));
$start = date("h:i:s",strtotime($start_time));
$diff = strtotime($end) - strtotime($start);
//convert to min and sec
$convert_min = $diff/60;
$convert_sec = $diff % 60;//seconds
//convert to hours and min
$convert_hr = floor($convert_min/60);//hours
$remainder = floor($convert_min % 60);//minutes
$total_visit = $convert_hr.":".$remainder;
You can use the DateTime object in php, which has loads of methods for manipulating dates.
DateTime::createFromFormat http://www.php.net/manual/en/datetime.createfromformat.php and DateTime::diff http://www.php.net/manual/en/datetime.diff.php would be the functions you would need to perform this task.
$date1 = DateTime::createFromFormat('j-M-Y H:i', '15-Feb-2009 12:45');
$date2 = DateTime::createFromFormat('j-M-Y H:i', '15-Feb-2009 13:45');
$interval = $date1->diff($date2);
echo $interval->format('H:i');
strtotime(date($arrival_date)) - strtotime(date($departure_date));
Will give you the time diff in secounds, then you can manipulate that as you wish.
What's the most precise function you have come across to work out an age from the users date of birth. I have the following code and was wondering how it could be improved as it doesn't support all date formats and not sure if it's the most accurate function either (DateTime compliance would be nice).
function getAge($birthday) {
return floor((strtotime(date('d-m-Y')) - strtotime($date))/(60*60*24*365.2421896));
}
$birthday = new DateTime($birthday);
$interval = $birthday->diff(new DateTime);
echo $interval->y;
Should work
Check this
<?php
$c= date('Y');
$y= date('Y',strtotime('1988-12-29'));
echo $c-$y;
?>
Use this code to have full age including years, months and days-
<?php
//full age calulator
$bday = new DateTime('02.08.1991');//dd.mm.yyyy
$today = new DateTime('00:00:00'); // Current date
$diff = $today->diff($bday);
printf('%d years, %d month, %d days', $diff->y, $diff->m, $diff->d);
?>
Try using DateTime for this:
$now = new DateTime();
$birthday = new DateTime('1973-04-18 09:48:00');
echo $now->diff($birthday)->format('%y years'); // 49 years
See it in action
This works:
<?
$date = date_create('1984-10-26');
$interval = $date->diff(new DateTime);
echo $interval->y;
?>
If you tell me in what format your $birthday variable comes I will give you exact solution
WTF?
strtotime(date('d-m-Y'))
So you generate a date string from the current timestamp, then convert the date string back into a timestamp?
BTW, one of the reasons it's not working is that strtotime() assumes numeric dates to be in the format m/d/y (i.e. the US format of date first). Another reason is that the parameter ($birthday) is not used in the formula.
Change the $date to $birthday.
For supper accuracy you need to account for the leap year factor:
function get_age($dob_day,$dob_month,$dob_year){
$year = gmdate('Y');
$month = gmdate('m');
$day = gmdate('d');
//seconds in a day = 86400
$days_in_between = (mktime(0,0,0,$month,$day,$year) - mktime(0,0,0,$dob_month,$dob_day,$dob_year))/86400;
$age_float = $days_in_between / 365.242199; // Account for leap year
$age = (int)($age_float); // Remove decimal places without rounding up once number is + .5
return $age;
}
So use:
echo get_date(31,01,1985);
or whatever...
N.B. To see your EXACT age to the decimal
return $age_float
instead.
This function works fine.
function age($birthday){
list($day,$month,$year) = explode("/",$birthday);
$year_diff = date("Y") - $year;
$month_diff = date("m") - $month;
$day_diff = date("d") - $day;
if ($day_diff < 0 && $month_diff==0){$year_diff--;}
if ($day_diff < 0 && $month_diff < 0){$year_diff--;}
return $year_diff;
}
See BLOG Post
Here is my long/detailed version (you can make it shorter if you want):
$timestamp_birthdate = mktime(9, 0, 0, $birthdate_month, $birthdate_day, $birthdate_year);
$timestamp_now = time();
$difference_seconds = $timestamp_now-$timestamp_birthdate;
$difference_minutes = $difference_seconds/60;
$difference_hours = $difference_minutes/60;
$difference_days = $difference_hours/24;
$difference_years = $difference_days/365;
I'm looking for a way to calculate the age of a person, given their DOB in the format dd/mm/yyyy.
I was using the following function which worked fine for several months until some kind of glitch caused the while loop to never end and grind the entire site to a halt. Since there are almost 100,000 DOBs going through this function several times a day, it's hard to pin down what was causing this.
Does anyone have a more reliable way of calculating the age?
//replace / with - so strtotime works
$dob = strtotime(str_replace("/","-",$birthdayDate));
$tdate = time();
$age = 0;
while( $tdate > $dob = strtotime('+1 year', $dob))
{
++$age;
}
return $age;
EDIT: this function seems to work OK some of the time, but returns "40" for a DOB of 14/09/1986
return floor((time() - strtotime($birthdayDate))/31556926);
This works fine.
<?php
//date in mm/dd/yyyy format; or it can be in other formats as well
$birthDate = "12/17/1983";
//explode the date to get month, day and year
$birthDate = explode("/", $birthDate);
//get age from date or birthdate
$age = (date("md", date("U", mktime(0, 0, 0, $birthDate[0], $birthDate[1], $birthDate[2]))) > date("md")
? ((date("Y") - $birthDate[2]) - 1)
: (date("Y") - $birthDate[2]));
echo "Age is:" . $age;
?>
$tz = new DateTimeZone('Europe/Brussels');
$age = DateTime::createFromFormat('d/m/Y', '12/02/1973', $tz)
->diff(new DateTime('now', $tz))
->y;
As of PHP 5.3.0 you can use the handy DateTime::createFromFormat to ensure that your date does not get mistaken for m/d/Y format and the DateInterval class (via DateTime::diff) to get the number of years between now and the target date.
$date = new DateTime($bithdayDate);
$now = new DateTime();
$interval = $now->diff($date);
return $interval->y;
I use Date/Time for this:
$age = date_diff(date_create($bdate), date_create('now'))->y;
Simple method for calculating Age from dob:
$_age = floor((time() - strtotime('1986-09-16')) / 31556926);
31556926 is the number of seconds in a year.
I find this works and is simple.
Subtract from 1970 because strtotime calculates time from 1970-01-01 (http://php.net/manual/en/function.strtotime.php)
function getAge($date) {
return intval(date('Y', time() - strtotime($date))) - 1970;
}
Results:
Current Time: 2015-10-22 10:04:23
getAge('2005-10-22') // => 10
getAge('1997-10-22 10:06:52') // one 1s before => 17
getAge('1997-10-22 10:06:50') // one 1s after => 18
getAge('1985-02-04') // => 30
getAge('1920-02-29') // => 95
// Age Calculator
function getAge($dob,$condate){
$birthdate = new DateTime(date("Y-m-d", strtotime(implode('-', array_reverse(explode('/', $dob))))));
$today= new DateTime(date("Y-m-d", strtotime(implode('-', array_reverse(explode('/', $condate))))));
$age = $birthdate->diff($today)->y;
return $age;
}
$dob='06/06/1996'; //date of Birth
$condate='07/02/16'; //Certain fix Date of Age
echo getAge($dob,$condate);
Write a PHP script to calculate the current age of a person.
Sample date of birth : 11.4.1987
Sample Solution:
PHP Code:
<?php
$bday = new DateTime('11.4.1987'); // Your date of birth
$today = new Datetime(date('m.d.y'));
$diff = $today->diff($bday);
printf(' Your age : %d years, %d month, %d days', $diff->y, $diff->m, $diff->d);
printf("\n");
?>
Sample Output:
Your age : 30 years, 3 month, 0 days
Figured I'd throw this on here since this seems to be most popular form of this question.
I ran a 100 year comparison on 3 of the most popular types of age funcs i could find for PHP and posted my results (as well as the functions) to my blog.
As you can see there, all 3 funcs preform well with just a slight difference on the 2nd function. My suggestion based on my results is to use the 3rd function unless you want to do something specific on a person's birthday, in which case the 1st function provides a simple way to do exactly that.
Found small issue with test, and another issue with 2nd method! Update coming to blog soon! For now, I'd take note, 2nd method is still most popular one I find online, and yet still the one I'm finding the most inaccuracies with!
My suggestions after my 100 year review:
If you want something more elongated so that you can include occasions like birthdays and such:
function getAge($date) { // Y-m-d format
$now = explode("-", date('Y-m-d'));
$dob = explode("-", $date);
$dif = $now[0] - $dob[0];
if ($dob[1] > $now[1]) { // birthday month has not hit this year
$dif -= 1;
}
elseif ($dob[1] == $now[1]) { // birthday month is this month, check day
if ($dob[2] > $now[2]) {
$dif -= 1;
}
elseif ($dob[2] == $now[2]) { // Happy Birthday!
$dif = $dif." Happy Birthday!";
};
};
return $dif;
}
getAge('1980-02-29');
But if you just simply want to know the age and nothing more, then:
function getAge($date) { // Y-m-d format
return intval(substr(date('Ymd') - date('Ymd', strtotime($date)), 0, -4));
}
getAge('1980-02-29');
See BLOG
A key note about the strtotime method:
Note:
Dates in the m/d/y or d-m-y formats are disambiguated by looking at the
separator between the various components: if the separator is a slash (/),
then the American m/d/y is assumed; whereas if the separator is a dash (-)
or a dot (.), then the European d-m-y format is assumed. If, however, the
year is given in a two digit format and the separator is a dash (-, the date
string is parsed as y-m-d.
To avoid potential ambiguity, it's best to use ISO 8601 (YYYY-MM-DD) dates or
DateTime::createFromFormat() when possible.
You can use the Carbon library, which is an API extension for DateTime.
You can:
function calculate_age($date) {
$date = new \Carbon\Carbon($date);
return (int) $date->diffInYears();
}
or:
$age = (new \Carbon\Carbon($date))->age;
If you want to caculate the Age of using the dob, you can also use this function.
It uses the DateTime object.
function calcutateAge($dob){
$dob = date("Y-m-d",strtotime($dob));
$dobObject = new DateTime($dob);
$nowObject = new DateTime();
$diff = $dobObject->diff($nowObject);
return $diff->y;
}
If you don't need great precision, just the number of years, you could consider using the code below ...
print floor((time() - strtotime("1971-11-20")) / (60*60*24*365));
You only need to put this into a function and replace the date "1971-11-20" with a variable.
Please note that precision of the code above is not high because of the leap years, i.e. about every 4 years the days are 366 instead of 365. The expression 60*60*24*365 calculates the number of seconds in one year - you can replace it with 31536000.
Another important thing is that because of the use of UNIX Timestamp it has both the Year 1901 and Year 2038 problem which means the the expression above will not work correctly for dates before year 1901 and after year 2038.
If you can live with the limitations mentioned above that code should work for you.
$birthday_timestamp = strtotime('1988-12-10');
// Calculates age correctly
// Just need birthday in timestamp
$age = date('md', $birthday_timestamp) > date('md') ? date('Y') - date('Y', $birthday_timestamp) - 1 : date('Y') - date('Y', $birthday_timestamp);
//replace / with - so strtotime works
$dob = strtotime(str_replace("/","-",$birthdayDate));
$tdate = time();
return date('Y', $tdate) - date('Y', $dob);
function dob ($birthday){
list($day,$month,$year) = explode("/",$birthday);
$year_diff = date("Y") - $year;
$month_diff = date("m") - $month;
$day_diff = date("d") - $day;
if ($day_diff < 0 || $month_diff < 0)
$year_diff--;
return $year_diff;
}
I have found this script reliable. It takes the date format as YYYY-mm-dd, but it could be modified for other formats pretty easily.
/*
* Get age from dob
* #param dob string The dob to validate in mysql format (yyyy-mm-dd)
* #return integer The age in years as of the current date
*/
function getAge($dob) {
//calculate years of age (input string: YYYY-MM-DD)
list($year, $month, $day) = explode("-", $dob);
$year_diff = date("Y") - $year;
$month_diff = date("m") - $month;
$day_diff = date("d") - $day;
if ($day_diff < 0 || $month_diff < 0)
$year_diff--;
return $year_diff;
}
i18n :
function getAge($birthdate, $pattern = 'eu')
{
$patterns = array(
'eu' => 'd/m/Y',
'mysql' => 'Y-m-d',
'us' => 'm/d/Y',
);
$now = new DateTime();
$in = DateTime::createFromFormat($patterns[$pattern], $birthdate);
$interval = $now->diff($in);
return $interval->y;
}
// Usage
echo getAge('05/29/1984', 'us');
// return 28
Try any of these using DateTime object
$hours_in_day = 24;
$minutes_in_hour= 60;
$seconds_in_mins= 60;
$birth_date = new DateTime("1988-07-31T00:00:00");
$current_date = new DateTime();
$diff = $birth_date->diff($current_date);
echo $years = $diff->y . " years " . $diff->m . " months " . $diff->d . " day(s)"; echo "<br/>";
echo $months = ($diff->y * 12) + $diff->m . " months " . $diff->d . " day(s)"; echo "<br/>";
echo $weeks = floor($diff->days/7) . " weeks " . $diff->d%7 . " day(s)"; echo "<br/>";
echo $days = $diff->days . " days"; echo "<br/>";
echo $hours = $diff->h + ($diff->days * $hours_in_day) . " hours"; echo "<br/>";
echo $mins = $diff->h + ($diff->days * $hours_in_day * $minutes_in_hour) . " minutest"; echo "<br/>";
echo $seconds = $diff->h + ($diff->days * $hours_in_day * $minutes_in_hour * $seconds_in_mins) . " seconds"; echo "<br/>";
Reference http://www.calculator.net/age-calculator.html
this is my function to calculating DOB with the specific return of age by year, month, and day
function ageDOB($y=2014,$m=12,$d=31){ /* $y = year, $m = month, $d = day */
date_default_timezone_set("Asia/Jakarta"); /* can change with others time zone */
$ageY = date("Y")-intval($y);
$ageM = date("n")-intval($m);
$ageD = date("j")-intval($d);
if ($ageD < 0){
$ageD = $ageD += date("t");
$ageM--;
}
if ($ageM < 0){
$ageM+=12;
$ageY--;
}
if ($ageY < 0){ $ageD = $ageM = $ageY = -1; }
return array( 'y'=>$ageY, 'm'=>$ageM, 'd'=>$ageD );
}
this how to use it
$age = ageDOB(1984,5,8); /* with my local time is 2014-07-01 */
echo sprintf("age = %d years %d months %d days",$age['y'],$age['m'],$age['d']); /* output -> age = 29 year 1 month 24 day */
This function will return the age in years. Input value is a date formated (YYYY-MM-DD) day of birth string eg: 2000-01-01
It works with day - precision
function getAge($dob) {
//calculate years of age (input string: YYYY-MM-DD)
list($year, $month, $day) = explode("-", $dob);
$year_diff = date("Y") - $year;
$month_diff = date("m") - $month;
$day_diff = date("d") - $day;
// if we are any month before the birthdate: year - 1
// OR if we are in the month of birth but on a day
// before the actual birth day: year - 1
if ( ($month_diff < 0 ) || ($month_diff === 0 && $day_diff < 0))
$year_diff--;
return $year_diff;
}
Cheers, nira
If you want to only get fullyears as age, there is a supersimple way on doing that. treat dates formatted as 'YYYYMMDD' as numbers and substract them. After that cancel out the MMDD part by dividing the result with 10000 and floor it down. Simple and never fails, even takes to account leapyears and your current server time ;)
Since birthdays or mostly provided by full dates on birth location and they are relevant to CURRENT LOCAL TIME (where the age check is actually done).
$now = date['Ymd'];
$birthday = '19780917'; #september 17th, 1978
$age = floor(($now-$birthday)/10000);
so if you want to check if someone is 18 or 21 or below 100 on your timezone (nevermind the origin timezone) by birthday, this is my way to do this
If you can't seem to use some of the newer functions, here's something I whipped up. Probably more than you need, and I'm sure there are better ways, but it's easy to read, so it should do the job:
function get_age($date, $units='years')
{
$modifier = date('n') - date('n', strtotime($date)) ? 1 : (date('j') - date('j', strtotime($date)) ? 1 : 0);
$seconds = (time()-strtotime($date));
$years = (date('Y')-date('Y', strtotime($date))-$modifier);
switch($units)
{
case 'seconds':
return $seconds;
case 'minutes':
return round($seconds/60);
case 'hours':
return round($seconds/60/60);
case 'days':
return round($seconds/60/60/24);
case 'months':
return ($years*12+date('n'));
case 'decades':
return ($years/10);
case 'centuries':
return ($years/100);
case 'years':
default:
return $years;
}
}
Example Use:
echo 'I am '.get_age('September 19th, 1984', 'days').' days old';
Hope this helps.
Due to leap year, it is not wise just to subtract one date from another and floor it to number of years. To calculate the age like the humans, you will need something like this:
$birthday_date = '1977-04-01';
$age = date('Y') - substr($birthday_date, 0, 4);
if (strtotime(date('Y-m-d')) - strtotime(date('Y') . substr($birthday_date, 4, 6)) < 0)
{
$age--;
}
The following works great for me and seems to be a lot simpler than the examples that have already been given.
$dob_date = "01";
$dob_month = "01";
$dob_year = "1970";
$year = gmdate("Y");
$month = gmdate("m");
$day = gmdate("d");
$age = $year-$dob_year; // $age calculates the user's age determined by only the year
if($month < $dob_month) { // this checks if the current month is before the user's month of birth
$age = $age-1;
} else if($month == $dob_month && $day >= $dob_date) { // this checks if the current month is the same as the user's month of birth and then checks if it is the user's birthday or if it is after it
$age = $age;
} else if($month == $dob_month && $day < $dob_date) { //this checks if the current month is the user's month of birth and checks if it before the user's birthday
$age = $age-1;
} else {
$age = $age;
}
I've tested and actively use this code, it might seem a little cumbersome but it is very simple to use and edit and is quite accurate.
Following the first logic, you have to use = in the comparison.
<?php
function age($birthdate) {
$birthdate = strtotime($birthdate);
$now = time();
$age = 0;
while ($now >= ($birthdate = strtotime("+1 YEAR", $birthdate))) {
$age++;
}
return $age;
}
// Usage:
echo age(implode("-",array_reverse(explode("/",'14/09/1986')))); // format yyyy-mm-dd is safe!
echo age("-10 YEARS") // without = in the comparison, will returns 9.
?>
It is a problem when you use strtotime with DD/MM/YYYY. You cant use that format. Instead of it you can use MM/DD/YYYY (or many others like YYYYMMDD or YYYY-MM-DD) and it should work properly.
How about launching this query and having MySQL calculating it for you:
SELECT
username
,date_of_birth
,(PERIOD_DIFF( DATE_FORMAT(CURDATE(), '%Y%m') , DATE_FORMAT(date_of_birth, '%Y%m') )) DIV 12 AS years
,(PERIOD_DIFF( DATE_FORMAT(CURDATE(), '%Y%m') , DATE_FORMAT(date_of_birth, '%Y%m') )) MOD 12 AS months
FROM users
Result:
r2d2, 1986-12-23 00:00:00, 27 , 6
The user has 27 years and 6 months (it counts an entire month)
I did it like this.
$geboortedatum = 1980-01-30 00:00:00;
echo leeftijd($geboortedatum)
function leeftijd($geboortedatum) {
$leeftijd = date('Y')-date('Y', strtotime($geboortedatum));
if (date('m')<date('m', strtotime($geboortedatum)))
$leeftijd = $leeftijd-1;
elseif (date('m')==date('m', strtotime($geboortedatum)))
if (date('d')<date('d', strtotime($geboortedatum)))
$leeftijd = $leeftijd-1;
return $leeftijd;
}
The top answer for this is OK but only calualtes the year a person was born, I tweaked it for my own purposes to work out the day and month. But thought it was worth sharing.
This works by taken a timestamp of the the users DOB, but feel free to change that
$birthDate = date('d-m-Y',$usersDOBtimestamp);
$currentDate = date('d-m-Y', time());
//explode the date to get month, day and year
$birthDate = explode("-", $birthDate);
$currentDate = explode("-", $currentDate);
$birthDate[0] = ltrim($birthDate[0],'0');
$currentDate[0] = ltrim($currentDate[0],'0');
//that gets a rough age
$age = $currentDate[2] - $birthDate[2];
//check if month has passed
if($birthDate[1] > $currentDate[1]){
//user birthday has not passed
$age = $age - 1;
} else if($birthDate[1] == $currentDate[1]){
//check if birthday is in current month
if($birthDate[0] > $currentDate[0]){
$age - 1;
}
}
echo $age;
Here is the process that is more simple and works both for the formats dd/mm/yyyy and dd-mm-yyyy. This is working great for me:
<?php
$birthday = '26/04/1994';
$dob = strtotime(str_replace("/", "-", $birthday));
$tdate = time();
echo date('Y', $tdate) - date('Y', $dob);
?>