Adding months to a date and insert into database - php

i'm trying to add X month to a date taken from my database
$sql_batch = "SELECT * FROM mgm_subscription WHERE status = '1'"
$query_batch = mysql_query($sql_batch);
$row_batch = mysql_fetch_array($query_batch);
$addMonth = 3;
$startDate = $row_batch['start_month'];
$endDate = strtotime('+'.$addMonth.' month', $startMonth); // add number of days from form
$endDate = date('m/d/y H:i:s', $endDate );
$sql_date = "INSERT INTO user_subscription (user_id, start_month, end_month, sub_status) VALUES ('".$usercode2."','".$startDate."','".$endDate."', '')";
$query_date = mysql_query($sql_date);
NULL was inserted into the end_month.
start_month and end_month is DATE type in the mysql
how do i fix this? tq.

If I understood your question, your $endDate should be
$endDate = date('Y-m-d', strtotime($startDate.' +'.$addMonth.' months'));
So this will equate to:
$endDate = $startDate + 3 months /* in Y-m-d format */
EDIT: Just saw that your column datatype is Date. This would mean that you can't store timestamp in your date. It has to be Y-m-d format only as that is the valid mysql format supported.

You insert $endMonth a value(number of days from form) then you try to replace it ($endMonth) and you call back your replaced variable..
$endMonth = strtotime('+'.$addMonth.' month', $startMonth); // add number of days from form
$endMonth = date('m/d/y H:i:s', $endMonth);
It will return null value.. My suggestion, try to put other variable to prevent duplicate value or missing data

You only mention adding X months. Maybe I misunderstood your question, but if all you care about is the month, I would do the following:
if ($startMonth === 'January') {
$monthNumber = 1;
} else if ($startMonth === 'February') {
$monthNumber = 2;
} //Up to November then finish with {
else {
$monthNumber = 12;//December
}
$newMonthNumber = $monthNumber + $addMonth;
if ($newMonthNumber % 12 == 1) {
$endMonth = 'January';
} else if ($newMonthNumber % 12 == 1) {
$endMonth = 'February';
} //Up to November then finish with {
else {
$endMonth = 'December';
}
$sql_date = "INSERT INTO user_subscription (user_id, start_month, end_month, sub_status) VALUES ('".$usercode2."','".$startMonth."','".$endMonth."', '')";
$query_date = mysql_query($sql_date);

Related

cant insert the difference of this into table

this is my insert section the $total_minutes and $total_hour cant be inserted in the table
$year = $_POST['year'];
$month = $_POST['month'];
$day = $_POST['day'];
$hour = $_POST['hour'];
$min = $_POST['min'];
$sec = $_POST['sec'];
$year1 = $_POST['year1'];
$month1 = $_POST['month1'];
$day1 = $_POST['day1'];
$hour1 = $_POST['hour1'];
$min1 = $_POST['min1'];
$sec1 = $_POST['sec1'];
$time_in = $year.'-'.$month.'-'.$day.' '.$hour.'-'.$min.'-'.$sec;
$time_out = $year1.'-'.$month1.'-'.$day1.' '.$hour1.'-'.$min1.'-'.$sec1;
$total_minutes = $total_min;
$total_hour = $total_hr;
$sql = "INSERT INTO time (year, month, day, hour, min, sec, year1, month1, day1, hour1, min1, sec1, time_in, time_out, total_minutes, total_hour)
VALUES
('$year','$month','$day','$hour','$min','$sec','$year1','$month1','$day1','$hour1','$min1','$sec1','$time_in','$time_out', '$total_minutes', '$total_hour')";
how can i add this in my table?
minutes
$datetime1 = strtotime($row['time_in']); //year-month-day hr:min:sec timein
$datetime2 = strtotime($row['time_out']); //year-month-day hr:min:sec timeout
$interval = abs($datetime2 - $datetime1);
$total_min = round($interval / 60);
$total_minutes = $total_min;
hour
function convertToHoursMins($total_minutes, $format = '%02d:%02d') {
if ($total_minutes < 1) {
return;
}
$hours = floor($total_minutes / 60);
$wmin = ($total_minutes % 60);
return sprintf($format, $hours, $wmin);
}
$total_hr = convertToHoursMins($total_minutes, '%02d hours %02d minutes');
$total_hour = $total_hr;
im new and i wanted a simple answer
Use MySQL TIMEDIFF() function to get the answer. Instead of PHP, MySQL Function gives the result in very easiest manner.
$datetime1 = strtotime($row['time_in']); //year-month-day hr:min:sec timein
$datetime2 = strtotime($row['time_out']); //year-month-day hr:min:sec timeout
$timeInterval = mysql_query("SELECT TIMEDIFF($datetime2, $datetime1)");
$timeArray = explode(":", $timeInterval);
Hope this may help you :)
You have to convert your datetime1 and datetime2 in this format first :
datetime1 = 2012-01-01 12:00:00;
datetime2 = 2012-01-02 13:00:00;
Then in my sql insert query directly insert value from following functions :
TIMESTAMPDIFF(HOUR, datetime2, datetime1) // For Hours Calculation
TIMESTAMPDIFF(MINUTE,datetime2, datetime1) // For Minutes Calculation
Hope this may help you :)

Am not able to check if month == equal datetime

I am trying to show results of each month.
Im having this for loop:
foreach ($overview as $day) {
$year = date("Y") - 1;
if ($day->user == $info->id) {
$startDate = new DateTime($day->Calendar_startdate);
$endDate = new DateTime($day->Calendar_enddate);
$s = $startDate->format('Y-m-d');
$e = $endDate->format('Y-m-d');
if ($s > $year) {
$workdays = number_of_working_days($s, $e);
$daysleft = $daysleft + $workdays;
} else {
}
}
}
This for loop is also in an if statement which echos the months.
Now I need to let it work for the months January, February etc...
I am able to not show results if in the previous year which works well.
If you want to compare $s with $year just change $year to :
$time = new DateTime('now');
/*** you can use `now` for today
/* or you can change to a fixed date exmp: 2016-01-01
*/
$year = $time->modify('-1 year')->format('Y-m-d');
Than you can compare $s > $year
I fixed by checking each month if it contained for example -01-
DB::table('Calendar')->where('Calendar_startdate', 'like','%' . $monthnumber . '%')->where('user', $info->id)->where('Calendar_type',2)->get();

Need to put date within quotes

I'm trying to pass a date to a function that calculates the age of a person. However, the date is in Y-m-d format in the database, and I need to pass it in "Y-m-d" format. I have tried string concatenation, but that failed, maybe because it just operated the numbers using minus(-) operator. Kindly let me know how to do the same.
I am fetching the DOB in $dob variable, and passing it to CalculateAge($dateofbirth) function
Here is the code:
function CalculateAge($BirthDate)
{
// Put the year, month and day in separate variables
list($Year, $Month, $Day) = explode("-", $BirthDate);
//echo $Year;
$YearDiff = date("Y") - $Year;
// If the birthday hasn't arrived yet this year, the person is one year younger
if(date("m") < $Month || (date("m") == $Month && date("d") < $Day))
{
$YearDiff--;
}
if(date("m") > $Month || date("m") == $Month)
$MonthDiff = date("m") - $Month;
else
$MonthDiff = 12 - $Month + date("m");
$age = $YearDiff + $MonthDiff/12;
return $age;
}
$dob = mysql_query("SELECT date_of_birth FROM kids_informations WHERE user_id = '$usid'");
$rs = CalculateAge($dob);
This would probably work -
$result = mysql_query("SELECT date_of_birth FROM kids_informations WHERE user_id = '$usid'");
while($row = mysql_fetch_array($result))
{
$dob = $row['date_of_birth'];
}
$dob = "\"".$dob."\"";
$rs = CalculateAge($dob);
use this: echo date("\"Y-m-d\"");

Next business day of given date in PHP

Does anyone have a PHP snippet to calculate the next business day for a given date?
How does, for example, YYYY-MM-DD need to be converted to find out the next business day?
Example:
For 03.04.2011 (DD-MM-YYYY) the next business day is 04.04.2011.
For 08.04.2011 the next business day is 11.04.2011.
This is the variable containing the date I need to know the next business day for
$cubeTime['time'];
Variable contains: 2011-04-01
result of the snippet should be: 2011-04-04
Next Weekday
This finds the next weekday from a specific date (not including Saturday or Sunday):
echo date('Y-m-d', strtotime('2011-04-05 +1 Weekday'));
You could also do it with a date variable of course:
$myDate = '2011-04-05';
echo date('Y-m-d', strtotime($myDate . ' +1 Weekday'));
UPDATE: Or, if you have access to PHP's DateTime class (very likely):
$date = new DateTime('2018-01-27');
$date->modify('+7 weekday');
echo $date->format('Y-m-d');
Want to Skip Holidays?:
Although the original poster mentioned "I don't need to consider holidays", if you DO happen to want to ignore holidays, just remember - "Holidays" is just an array of whatever dates you don't want to include and differs by country, region, company, person...etc.
Simply put the above code into a function that excludes/loops past the dates you don't want included. Something like this:
$tmpDate = '2015-06-22';
$holidays = ['2015-07-04', '2015-10-31', '2015-12-25'];
$i = 1;
$nextBusinessDay = date('Y-m-d', strtotime($tmpDate . ' +' . $i . ' Weekday'));
while (in_array($nextBusinessDay, $holidays)) {
$i++;
$nextBusinessDay = date('Y-m-d', strtotime($tmpDate . ' +' . $i . ' Weekday'));
}
I'm sure the above code can be simplified or shortened if you want. I tried to write it in an easy-to-understand way.
For UK holidays you can use
https://www.gov.uk/bank-holidays#england-and-wales
The ICS format data is easy to parse. My suggestion is...
# $date must be in YYYY-MM-DD format
# You can pass in either an array of holidays in YYYYMMDD format
# OR a URL for a .ics file containing holidays
# this defaults to the UK government holiday data for England and Wales
function addBusinessDays($date,$numDays=1,$holidays='') {
if ($holidays==='') $holidays = 'https://www.gov.uk/bank-holidays/england-and-wales.ics';
if (!is_array($holidays)) {
$ch = curl_init($holidays);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
$ics = curl_exec($ch);
curl_close($ch);
$ics = explode("\n",$ics);
$ics = preg_grep('/^DTSTART;/',$ics);
$holidays = preg_replace('/^DTSTART;VALUE=DATE:(\\d{4})(\\d{2})(\\d{2}).*/s','$1-$2-$3',$ics);
}
$addDay = 0;
while ($numDays--) {
while (true) {
$addDay++;
$newDate = date('Y-m-d', strtotime("$date +$addDay Days"));
$newDayOfWeek = date('w', strtotime($newDate));
if ( $newDayOfWeek>0 && $newDayOfWeek<6 && !in_array($newDate,$holidays)) break;
}
}
return $newDate;
}
function next_business_day($date) {
$add_day = 0;
do {
$add_day++;
$new_date = date('Y-m-d', strtotime("$date +$add_day Days"));
$new_day_of_week = date('w', strtotime($new_date));
} while($new_day_of_week == 6 || $new_day_of_week == 0);
return $new_date;
}
This function should ignore weekends (6 = Saturday and 0 = Sunday).
This function will calculate the business day in the future or past. Arguments are number of days, forward (1) or backwards(0), and a date. If no date is supplied todays date will be used:
// returned $date Y/m/d
function work_days_from_date($days, $forward, $date=NULL)
{
if(!$date)
{
$date = date('Y-m-d'); // if no date given, use todays date
}
while ($days != 0)
{
$forward == 1 ? $day = strtotime($date.' +1 day') : $day = strtotime($date.' -1 day');
$date = date('Y-m-d',$day);
if( date('N', strtotime($date)) <= 5) // if it's a weekday
{
$days--;
}
}
return $date;
}
What you need to do is:
Convert the provided date into a timestamp.
Use this along with the or w or N formatters for PHP's date command to tell you what day of the week it is.
If it isn't a "business day", you can then increment the timestamp by a day (86400 seconds) and check again until you hit a business day.
N.B.: For this is really work, you'd also need to exclude any bank or public holidays, etc.
I stumbled apon this thread when I was working on a Danish website where I needed to code a "Next day delivery" PHP script.
Here is what I came up with (This will display the name of the next working day in Danish, and the next working + 1 if current time is more than a given limit)
$day["Mon"] = "Mandag";
$day["Tue"] = "Tirsdag";
$day["Wed"] = "Onsdag";
$day["Thu"] = "Torsdag";
$day["Fri"] = "Fredag";
$day["Sat"] = "Lørdag";
$day["Sun"] = "Søndag";
date_default_timezone_set('Europe/Copenhagen');
$date = date('l');
$checkTime = '1400';
$date2 = date(strtotime($date.' +1 Weekday'));
if( date( 'Hi' ) >= $checkTime) {
$date2 = date(strtotime($date.' +2 Weekday'));
}
if (date('l') == 'Saturday'){
$date2 = date(strtotime($date.' +2 Weekday'));
}
if (date('l') == 'Sunday') {
$date2 = date(strtotime($date.' +2 Weekday'));
}
echo '<p>Næste levering: <span>'.$day[date("D", $date2)].'</span></p>';
As you can see in the sample code $checkTime is where I set the time limit which determines if the next day delivery will be +1 working day or +2 working days.
'1400' = 14:00 hours
I know that the if statements can be made more compressed, but I show my code for people to easily understand the way it works.
I hope someone out there can use this little snippet.
Here is the best way to get business days (Mon-Fri) in PHP.
function days()
{
$week=array();
$weekday=["Monday","Tuesday","Wednesday","Thursday","Friday"];
foreach ($weekday as $key => $value)
{
$sort=$value." this week";
$day=date('D', strtotime($sort));
$date=date('d', strtotime($sort));
$year=date('Y-m-d', strtotime($sort));
$weeks['day']= $day;
$weeks['date']= $date;
$weeks['year']= $year;
$week[]=$weeks;
}
return $week;
}
Hope this will help you guys.
Thanks,.
See the example below:
$startDate = new DateTime( '2013-04-01' ); //intialize start date
$endDate = new DateTime( '2013-04-30' ); //initialize end date
$holiday = array('2013-04-11','2013-04-25'); //this is assumed list of holiday
$interval = new DateInterval('P1D'); // set the interval as 1 day
$daterange = new DatePeriod($startDate, $interval ,$endDate);
foreach($daterange as $date){
if($date->format("N") <6 AND !in_array($date->format("Y-m-d"),$holiday))
$result[] = $date->format("Y-m-d");
}
echo "<pre>";print_r($result);
For more info: http://goo.gl/YOsfPX
You could do something like this.
/**
* #param string $date
* #param DateTimeZone|null|null $DateTimeZone
* #return \NavigableDate\NavigableDateInterface
*/
function getNextBusinessDay(string $date, ? DateTimeZone $DateTimeZone = null):\NavigableDate\NavigableDateInterface
{
$Date = \NavigableDate\NavigableDateFacade::create($date, $DateTimeZone);
$NextDay = $Date->nextDay();
while(true)
{
$nextDayIndexInTheWeek = (int) $NextDay->format('N');
// check if the day is between Monday and Friday. In DateTime class php, Monday is 1 and Friday is 5
if ($nextDayIndexInTheWeek >= 1 && $nextDayIndexInTheWeek <= 5)
{
break;
}
$NextDay = $NextDay->nextDay();
}
return $NextDay;
}
$date = '2017-02-24';
$NextBussinessDay = getNextBusinessDay($date);
var_dump($NextBussinessDay->format('Y-m-d'));
Output:
string(10) "2017-02-27"
\NavigableDate\NavigableDateFacade::create($date, $DateTimeZone), is provided by php library available at https://packagist.org/packages/ishworkh/navigable-date. You need to first include this library in your project with composer or direct download.
I used below methods in PHP, strtotime() does not work specially in leap year February month.
public static function nextWorkingDay($date, $addDays = 1)
{
if (strlen(trim($date)) <= 10) {
$date = trim($date)." 09:00:00";
}
$date = new DateTime($date);
//Add days
$date->add(new DateInterval('P'.$addDays.'D'));
while ($date->format('N') >= 5)
{
$date->add(new DateInterval('P1D'));
}
return $date->format('Y-m-d H:i:s');
}
This solution for 5 working days (you can change if you required for 6 or 4 days working). if you want to exclude more days like holidays then just check another condition in while loop.
//
while ($date->format('N') >= 5 && !in_array($date->format('Y-m-d'), self::holidayArray()))

PHP calculate age

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);
?>

Categories