mktime

(PHP 4, PHP 5, PHP 7)

mktimeOblicza uniksowy znacznik czasu dla podanej daty

Opis

mktime ([ int $godzina = date("H") [, int $minuta = date("i") [, int $sekunda = date("s") [, int $miesiąc = date("n") [, int $dzień = date("j") [, int $rok = date("Y") [, int $czy_letni = -1 ]]]]]]] ) : int

Zwraca uniksowy znacznik czasu dla podanych argumentów. Znacznik czasu jest liczbą całkowitą będącą ilością sekund pomiędzy początkiem Epoki Uniksa (1 stycznia 1970 00:00:00 GMT) i określonym czasem.

Argumenty mogą być pomijane w kolejności od prawej do lewej, gdyż zostaną one ustawione na obecną wartość w lokalnej dacie i czasie.

Notatki

Informacja:

Od PHP 5.1, gdy wywołane bez argumentów, mktime() tworzy komunikat E_STRICT: użyj funkcji time() w takim wypadku.

Parametry

godzina

Liczba godzin relatywna do rozpoczęcia dnia określonego przez miesiąc, dzień i rok. Ujemne wartości odnoszą się do godzin przed północą zażądanego dnia. Wartości większe niż 23 odnoszą się do odpowiednich godzin w kolejnym dniu/dniach.

minuta

Liczba minut względem początku godziny. Wartości ujemne oznaczają minutę w poprzedniej godzinie. Wartości większe niż 59 oznaczają opowiednią minutę w kolejnej godzinie/godzinach.

sekunda

Liczba sekund względem początku minuty. Wartości ujemne oznaczają sekundę w poprzedniej minucie. Wartości większe niż 59 oznaczają opowiednią sekundę w kolejnej minucie/minutach.

miesiąc

Numer miesiąca liczony względem końca poprzedniego roku. Wartości od 1 do 12 oznaczają normalne miesiące kalendarzowe przetwarzanego roku. Wartości mniejsze od 1 (w tym ujemne) oznaczają miesiące w poprzednim roku, w odwrotnej kolejności, więc 0 to grudzień, -1 to listopad itd. Wartości większe niż 12 oznaczają odpowiedni miesiąc w kolejnym roku/latach.

dzień

Liczba dni względem końca poprzedniego miesiąca. Wartości od 1 do 28, 29, 30 lub 31 (zależnie od miesiąca) oznaczają normalne dni w danym miesiacu. Wartości mniejsze od 1 (w tym ujemne) oznaczają dni w poprzednim miesiącu, więc 0 to ostatni dzień poprzedniego miesiąca, -1 to dzień wcześnij itd. Wartości większe niż liczba dni w danym miesiącu oznaczają odpowiedni dzień w kolejnych miesiącach.

rok

Numer roku, może być dwu- lub czterocyfrowy, gdzie wartości 0-69 są mapowane do 2000-2069, a 70-100 do 1970-2000. Na systemach, gdzie time_t 32bitowym integerem ze znakiem, tak jak zazwyczaj dzisiaj, poprawny zakres dla parametru rok wynosi mniej więcej od 1901 do 2038. Jednakże przed PHP 5.1.0 ten zakres był ograniczony od 1970 do 2038 na niektórych systemach (np. Windows).

czy_letni

Można ustawić ten parametr na 1, jeżeli czas jest w ramach czasu letniego, 0 jeśli nie jest lub -1 (domyślnie) jeżeli nie wiadomo czy czas jest w czasie letnim, czy nie. Jeżeli tego nie wiadomo, to PHP próbuje sam to sprawdzić. Może to spowodować powstanie niespodziewanych (ale nie niepoprawnych) wyników. Niektóre czasy są niepoprawne jeżeli w systemie włączony jest czas letni lub czy_letni jest ustawiony na 1. Jeżeli włączony jest czas letni o godzinie np 2:00, to wszystkie czasy pomiędzy 2:00 i 3:00 są niepoprawne i mktime() zwraca nieokreśloną (zazwyczaj ujemną) wartość. Niektóre systemy (np. Solaris 8) włączają czas letni od północy, więc godzina 0:30 dnia, w którym aktywowano czas letni, jest rozpoznawana jako 23:30 dnia poprzedniego.

Informacja:

Od PHP 5.1.0 ten parametr został zdeprecjonowany. W wyniku tego, w zamian powinno się używać nowych możliwości obsługi stref czasowych.

Informacja:

Ten parametr został usunięty w PHP 7.0.0.

Zwracane wartości

mktime() zwraca uniksowy znacznik czasu dla podanych argumentów. Jeżeli argumenty są niepoprawne, funkcja zwraca FALSE (przed PHP 5.1 zwracała -1).

Błędy/Wyjątki

Każde wywołanie do funkcji date/time spowoduje wygenerowanie E_NOTICE jeśli strefa czasowa jest nieprawidłowa, lub/i wiadomość E_STRICT jeśli użyto ustawień systemu lub zmiennej środowiskowej TZ. Patrz także date_default_timezone_set()

Rejestr zmian

Wersja Opis
7.0.0 Parametr czy_letni został usunięty.
5.3.0 mktime() zgłasza komunikat E_DEPRECATED jeżeli użyto parametru czy_letni.
5.1.0 Parametr czy_letni został zdeprecjonowany. Funkcja zwraca FALSE w wypadku błędu, a nie -1, jak wcześniej. Naprawiono funkcję, aby akceptowała rok, miesiąc i dzień przekazane jako zero.
5.1.0 Gdy wywoływana bez argumentów, mktime() tworzy komunikat E_STRICT. Zamiast tego użyj funkcji time().
5.1.0

Teraz generuje błędy strefy czasowej o poziomie E_STRICT i E_NOTICE.

Przykłady

Przykład #1 Podstawowy przykład użycia mktime()

<?php
// Ustaw domyślną strefę czasową. Dostępne od PHP 5.1
date_default_timezone_set('UTC');

// Wyświetla: Pierwszy lipca 2000 wypada w: Saturday
echo "Pierwszy lipca 2000 wypada w: " date("l"mmktime(000712000));

// Wyświetli coś jak: 2006-04-05T01:02:03+00:00
echo date('c'mktime(123452006));
?>

Przykład #2 Przykład użycia mktime()

mktime() jest przydatne do operacji arytmetycznych na datach i walidacji dat, bo automatycznie liczy poprawną wartość dla wejścia spoza zakresu. Przykładowo, każda z poniższych linijek wyświetli łańcuch "Jan-01-1998".

<?php
echo date("M-d-Y"mktime(00012321997));
echo 
date("M-d-Y"mktime(0001311997));
echo 
date("M-d-Y"mktime(000111998));
echo 
date("M-d-Y"mktime(0001198));
?>

Przykład #3 Ostatni dzień miesiąca

Ostatni dzień dowolnego miesiąca może być wyrażony jako dzień "0" następnego miesiąca, a nie dzień -1. Oba poniższe przykłady wyświetlą łańcuch "Ostatni dzień w lutym 2000 to: 29".

<?php
$lastday 
mktime(000302000);
echo 
strftime("Ostatni dzień w lutym 2000 to: %d"$lastday);
$lastday mktime(0004, -312000);
echo 
strftime("Ostatni dzień w lutym 2000 to: %d"$lastday);
?>

Notatki

Uwaga

Przed PHP 5.1.0 ujemne znaczniki czasu nie były obsługiwane na żadnej znanej wersji systemu Window i w niektórych innych systemach. Z tego powodu zakres poprawnych lat był ograniczony od 1970 do 2038.

Zobacz też:

  • checkdate() - Waliduje datę gregoriańską
  • gmmktime() - Zwraca uniksowy znacznik czasu dla daty ze strefy GMT
  • date() - Formatuje lokalny czas/datę
  • time() - Zwraca aktualny uniksowy znacznik czasu

add a note add a note

User Contributed Notes 27 notes

up
48
Alan
15 years ago
Do remember that, counter-intuitively enough, the arguments for month and day are inversed (or middle-endian). A common mistake for Europeans seems to be to feed the date arguments in the expected order (big endian or little endian).

It's clear to see where this weird order comes from (even with the date being big endian the order for all arguments would still be mixed - it's obviously based on the American date format with the time "prefixed" to allow an easier shorthand) and why this wasn't changed (passing the values in the wrong order produces a valid, though unexpected, result in most cases), but it continues to be a source of confusion for me whenever I come back to PHP from other languages or libraries.
up
16
joseph dot andrew dot hughes at gmail dot com
16 years ago
Just a small thing to think about if you are only trying to pull the month out using mktime and date.  Make sure you place a 1 into day field.  Otherwise you will get incorrect dates when a month is followed by a month with less days when the day of the current month is higher then the max day of the month you are trying to find.. (Such as today being Jan 30th and trying to find the month Feb.)
up
13
Rad
10 years ago
Be careful passing zeros into mktime, in most cases a zero will count as the previous unit of time. The documentation explains this yet most of the comments here still use zeroes.

For example, if you pass the year 2013 into mktime, with zeroes for everything else, the outcome is probably not what you are looking for.

<?php
echo date('F jS, Y g:i:s a', mktime(0, 0, 0, 0, 0, 2013));
// November 30th, 2012 12:00:00 am
?>

Instead of using 0's, try 1's. This makes more sense (except for minutes/seconds). Maybe not as obvious of a purpose as zeroes to other programmers, though.

<?php
echo date('F jS, Y g:i:s a', mktime(1, 1, 1, 1, 1, 2013));
// January 1st, 2013 1:01:01 am
?>
up
6
developers at zeros dot co dot id
6 years ago
Please note, mktime requires an integer value, if you use date("H"), date("i"), date("s") as a value, which is actually have a leading zero, you may get "A non well formed numeric value encountered" notice. so you need some tricks like this

mktime( date("G"), intval(date("i")), intval(date("s"), date("n"), date("j"), date("Y") )

Since there are no minute & second without leading zero in the date function, we can use the intval() function or you can cast value type like this to force the value type.

(int) date("i")
up
6
phper
7 years ago
Please mind function is timezone dependent. Timezone independent funciton is gmmktime
up
6
thomas_corthals at hotmail dot com
15 years ago
It seems mktime() doesn't return negative timestamps on Linux systems with a version of glibc <= 2.3.3.
up
7
tom at chegg dot com
13 years ago
I was using the following to get a list of month names.

for ($i=1; $i<13; $i++) {
  echo date('F', mktime(0,0,0,$i) . ",";
}

Normally this outputs -
January,February,March,April,May,June,July,August,
September,October,November,December

However if today's date is the 31st you get instead:
January,March,March,May,May,July,July,August,October,
October,December,December

Why? Because Feb,Apr,June,Sept, and Nov don't have 31 days!

The fix, add the 5th parameter, don't let the day of month default to today's date:

  echo date('F', mktime(0,0,0,$i,1) . ",";
up
3
mh240873 at web dot de
9 years ago
Pay attention that not all days have the same number of seconds (86400s) if you are using date_default_timezone_set(..) and the used timezone has Daylight Saving Time (DST) e.g. "Europe/Berlin". Under PHP 5.5.16 I get the following results:

  $shortday  = mktime(23,59,59, '3','29','2015') - mktime(0,0,0, '3','29','2015) + 1; // result: 82800s  (86400s - 3600s)
  $normalDay = mktime(23,59,59, '1', '2','2015') - mktime(0,0,0, '1', '1','2015) + 1; // result: 86400s 
  $longDay   = mktime(23,59,59,'10','25','2015') - mktime(0,0,0,'10','25','2015) + 1; // result: 90000s  (86400s + 3600s)

Pitfall is noticeable if you are running an iterative loop with a code like:
   echo date( 'd.m.Y', $day );
   $day = $day + 86400;   // 86400 = 24*3600 - frequently used in PHP code

which results in wrong date if $day reaches 2015-10-25 (end of summer time in Germany):
    24.10.2015
    25.10.2015  
    25.10.2015   // Ups! Same date twice in calendar
    27.10.2015

You may workaround this by using date_default_timezone_set('UTC') where all days have the same number of seconds.
up
1
MarkAgius at markagius dot co dot uk
6 years ago
The following function moves all the parameters in order of most significant (biggest) to least significant (smallest) order.
Year is bigger than month. Month is bigger than day. Day bigger than hours...

Much less confusing than mktime order.

<?php
function mkTimestamp($year,$month,$day, $hours=0,$minutes=0,$seconds=0){
 
// Same as mktime() but parameters are in most significant to least significant order.
 
return mktime($hours,$minutes,$seconds, $month,$day,$year);
}
?>
up
1
ronnie dot kurniawan at gmail dot com
15 years ago
Add (and subtract) unixtime:

<?php
function utime_add($unixtime, $hr=0, $min=0, $sec=0, $mon=0, $day=0, $yr=0) {
 
$dt = localtime($unixtime, true);
 
$unixnewtime = mktime(
     
$dt['tm_hour']+$hr, $dt['tm_min']+$min, $dt['tm_sec']+$sec,
     
$dt['tm_mon']+1+$mon, $dt['tm_mday']+$day, $dt['tm_year']+1900+$yr);
  return
$unixnewtime;
}
?>
up
1
info at microweb dot lt
13 years ago
Function to generate array of dates between two dates (date range array)

<?php
function dates_range($date1, $date2)
{
   if (
$date1<$date2)
   {
      
$dates_range[]=$date1;
      
$date1=strtotime($date1);
      
$date2=strtotime($date2);
       while (
$date1!=$date2)
       {
          
$date1=mktime(0, 0, 0, date("m", $date1), date("d", $date1)+1, date("Y", $date1));
          
$dates_range[]=date('Y-m-d', $date1);
       }
   }
   return
$dates_range;
}

echo
'<pre>';
print_r(dates_range('2009-12-25', '2010-01-05'));
echo
'</pre>';
?>

[EDIT BY danbrown AT php DOT net: Contains a bugfix submitted by (carlosbuz2 AT gmail DOT com) on 04-MAR-2011, with the following note: The first date in array is incorrect.]
up
-1
PHPcoder at freemail dot ig3 dot net
16 years ago
The maximum possible date accepted by mktime() and gmmktime() is dependent on the current location time zone.

For example, the 32-bit timestamp overflow occurs at 2038-01-19T03:14:08+0000Z.  But if you're in a UTC -0500 time zone (such as EST in North America), the maximum accepted time before overflow (for older PHP versions on Windows) is 2038-01-18T22:14:07-0500Z, regardless of whether you're passing it to mktime() or gmmktime().
up
-3
rga at merchantpal dot com
17 years ago
You cannot simply subtract or add month VARs using mktime to obtain previous or next months as suggested in previous user comments (at least not with a DD > 28 anyway).

If the date is 03-31-2007, the following yeilds March as a previous month. Not what you wanted.

<?php
$dateMinusOneMonth
= mktime(0, 0, 0, (3-1), 312007 );
$lastmonth = date("n | F", $dateMinusOneMonth);
echo
$lastmonth;    //---> 3 | March
?>

mktime correctly gives you back the 3rd of March if you subtract 1 month from March 31 (there are only 28 days in Feb 07).

If you are just looking to do month and year arithmetic using mktime, you can use general days like 1 or 28 to do stuff like this:

<?php
$d_daysinmonth
= date('t', mktime(0,0,0,$myMonth,1,$myYear));     // how many days in month
$d_year = date('Y', mktime(0,0,0,$myMonth,1,$myYear));        // year
$d_isleapyear = date('L', mktime(0,0,0,$myMonth,1,$myYear));    // is YYYY a leapyear?

$d_firstdow = date('w', mktime(0,0,0,$myMonth,'1',$myYear));     // FIRST falls on what day of week (0-6)
$d_firstname = date('l', mktime(0,0,0,$myMonth,'1',$myYear));     // FIRST falls on what day of week Full Name

$d_month = date('n', mktime(0,0,0,$myMonth,28,$myYear));         // month of year (1-12)
$d_monthname = date('F', mktime(0,0,0,$myMonth,28,$myYear));         // Month Long name (July)
$d_month_previous = date('n', mktime(0,0,0,($myMonth-1),28,$myYear));         // PREVIOUS month of year (1-12)
$d_monthname_previous = date('F', mktime(0,0,0,($myMonth-1),28,$myYear));     // PREVIOUS Month Long name (July)
$d_month_next = date('n', mktime(0,0,0,($myMonth+1),28,$myYear));         // NEXT month of year (1-12)
$d_monthname_next = date('F', mktime(0,0,0,($myMonth+1),28,$myYear));         // NEXT Month Long name (July)
$d_year_previous = date('Y', mktime(0,0,0,$myMonth,28,($myYear-1)));        // PREVIOUS year
$d_year_next = date('Y', mktime(0,0,0,$myMonth,28,($myYear+1)));        // NEXT year

$d_weeksleft = (52 - $d_weekofyear);                     // how many weeks left in year
$d_daysinyear = $d_isleapyear ? 366 : 365;                // set correct days in year for leap years
$d_daysleft = ($d_daysinyear - $d_dayofyear);                // how many days left in year
?>
up
-3
A.Ross
7 years ago
What's odd is that mktime doesn't seem to support every possible year number. It's common sense that 2 digit (shortened) year numbers are interpreted in the range 1970..2069

However, when padded with zeroes, no such transformation should happen (at least that is the behaviour of other date functions). Unfortunately it does (until year 100 *inclusive*):

<?php
echo date("Y-m-d",mktime(0,0,0,1,1,"0001"));
// Expected: 0001-01-01
// Result:   2001-01-01      INCORRECT

echo date("Y-m-d",mktime(0,0,0,1,1,"0100"));
// Expected: 0100-01-01
// Result:   2000-01-01      INCORRECT

echo date("Y-m-d",mktime(0,0,0,1,1,"0101"));
// Expected: 0101-01-01
// Result:   0101-01-01      Correct
?>
up
-6
info at djdb dot be
10 years ago
raw date to clean timestamp
private function dateToTimestamp($date){
        $datefrom = explode(" ", $date);
        $value = array();
        if(strpos($datefrom[0], '-')){
            //print "issplit -";
            $value = explode("-", $datefrom[0]);
        }
        if(strpos($datefrom[0], '/')){
            //print "issplit /";
            $value = explode("/", $datefrom[0]);
        }
        /*if(){
           
        }*/
        if(strlen($value[2])==4){//13/12/2012
            //int mktime([hour[minute[second[month[day[year
            return mktime(0, 0, 0,$value[1],$value[0],$value[2]);
        }else{                  //2012/12/13
            //int mktime([hour[minute[second[month[day[year
            return mktime(0, 0, 0,$value[1],$value[2],$value[0]);
        }
    }
up
-6
yan
15 years ago
caculate days between two date

<?php
 
// end date is 2008 Oct. 11 00:00:00
 
$_endDate = mktime(0,0,0,11,10,2008);
 
// begin date is 2007 May 31 13:26:26
 
$_beginDate = mktime(13,26,26,05,31,2007);

 
$timestamp_diff= $_endDate-$_beginDate +1 ;
 
// how many days between those two date
 
$days_diff = $timestamp_diff/86400;

?>
up
-8
Stephen
17 years ago
There are several warnings here about using mktime() to determine a date difference because of daylight savings time. However, nobody seems to have mentioned the other obvious problem, which is leap years.

Leap years mean that any effort to use mktime() and time() to determine the age (positive or negative) of some timestamp in years will be flawed. There are some years that are 366 days long, therefore you cannot say that there is a set number of seconds per year.

Timestamps are good for determining *real* time, which is not the same thing as *human calendar* time. The Gregorian calendar is only an approximation of real time, which is tweaked with daylight savings time and leap years to make it conform more to humans' expectations of how time should or ought to work. Timestamps are not tweaked and therefore are the only authoritative way of recording in computers a proper order of succession of events, but they cannot be integrated with a Gregorian system unless you take both leap years and DST into account. Otherwise, you may get the wrong number of years when you are approaching a value of exactly X years.

As for PHP, you could still use timestamps as a way of determining age if you took into account not only DST but also whether or not each year is a leap year and adjusted your calculations accordingly. However, this could become messy and inefficient.

There is an alternative approach to calculating days given the day, month and year of the dates to be compared. Compare the years first, and then compare the month and day - if the month and day have already passed (or, if you like, if they match the current month and day), then add 1 to the total for the years.

This solution works because it stays within the Gregorian system and doesn't venture into the world of timestamps.

There is also the issue of leap seconds, but this will only arise if you literally need to get the *exact* age in seconds. In that case, of course, you would also need to verify that your timestamps are exactly correct and are not delayed by script processing time, plus you would need to determine whether your system conforms to UTC, etc. I expect this will hardly be an issue for anybody using PHP, however if you are interested there is an article on this issue on Wikipedia:

http://en.wikipedia.org/wiki/Leap_second
up
-6
ooogla at hotmail dot com
15 years ago
If you want to increment the day based on a variable when using a loop you can use this when you submit a form

1. Establish a start date and end date in two different variables

2. Get the number of days between a date

$ndays = (strtotime($_POST['edate']) - strtotime($_POST['sdate'])) / (60 * 60 * 24);

Then here is the string you slip in your loop

$nextday  = date('Y-m-d', mktime(0, 0, 0, date("m", strtotime($_POST['sdate']))  , date("d", strtotime($_POST['sdate']))+ $count, date("Y", strtotime($_POST['sdate']))));

$count is incremented by the loop.
up
-9
zfowler at unomaha dot edu
14 years ago
Proper way to convert Excel dates into PHP-friendly timestamps using mktime():

<?php
// The date 6/30/2009 is stored as 39994 in Excel
$days = 39994;

// But you must subtract 1 to get the correct timestamp
$ts = mktime(0,0,0,1,$days-1,1900);

// So, this would then match Excel's representation:
echo date("m/d/Y",$ts);
?>

Excel uses "number of days since Jan. 1, 1900" to store its dates.  It also treats 1900 as a leap year when it wasn't, thus there is an extra day which must be accounted for in PHP (and the rest of the world).  Subtracting 1 from Excel's number will fix this problem.
up
-12
cebleo at n-trance dot net
14 years ago
to ADD or SUBSTRACT times NOTE that if you dont specify the UTC zone your result is the difference +- your server UTC delay.

if you are ina utc/GMT +1

<?php
$hours_diff
= strtotime("20:00:00")-strtotime("19:00:00");
echo 
date('h:i', $hours_diff)." Hours";
?>

it shows: 02:00 Hours

but if you use a default UTC time:

<?php
date_default_timezone_set
('UTC');
$hours_diff = strtotime("20:00:00")-strtotime("19:00:00");
echo
"<br>". date('h:i', $hours_diff);
?>

it shows: 01:00 Hours.
up
-9
rlz
16 years ago
Finding out the number of days in a given month and year, accounting for leap years when February has more than 28 days.

<?php
function days_in_month($year, $month) {
    return(
date( "t", mktime( 0, 0, 0, $month, 1, $year) ) );
}
?>

Hope it helps a soul out there.
up
-9
Jacob Santos
11 years ago
Please note that incrementing a date using mktime in a loop is not proper. You could do it, except that there is a far better method found in the DateTime PHP class. Look at the documentation for DateTime::modify, DateTime::add (when supported) and DateTime::sub (when supported).

Also, adding seconds to a time is, well it isn't as easy as it seems, "Hey I'll just add 3600 seconds or 86400 seconds or x seconds!". The phrase once bitten, twice shy is quite applicable with the usage of adding seconds. If you ever had to 'fix' a time by calculating midnight to add the correct number of seconds, then you are doing it wrong.

Luckily, knowing is not a requirement, because DateTime and friends exists, removing the complexity for you.

So if given a choice of

mktime($seconds, $minutes, $hours+1);

and

$datetime->modify('+1 hour');

or

$datetime->add('P1H');

I'll go with the second choice, but probably not the third, unless I was using DateInterval::createFromDateString, so that other developers knew my intent.
up
-5
mktime_php at mailinator dot com
8 years ago
One practical and useful example of using negative values in mktime is the following:

<?php
//Considering today's date
echo date('Y-m-d'); //Prints: 2016-03-22
echo date('Y-m-d', mktime(0, 0, 0, date("m"), date("d")-42, date("Y"))); //Prints: 2016-02-09
?>

By using date outputs inside mktime and adding or subtracting from them may be simpler than using other methods (string concatenations or timestamp values) and less prone to human calculations' errors.
up
-3
utilmind
7 years ago
// here is the function which returns the Unix timestamp of last date of quarter, by  quarter number:
function last_day_of_quarter($q) {
  return mktime(0, 0, 0, floor($q*3), $q == 1 || $q == 4 ? 31 : 30);
}
up
-11
ionut dot bodea at eydos dot ro
15 years ago
Here is what I use to calculate age. It took me 30 minutes to write and it's quite accurate. What it has special is that it's calculating the number of days a year has (float number), by testing if a year is a leap one or not. This number is used to compute the age.

<?php
function get_age($date_start, $date_end) {
   
$t_lived = get_timestamp($date_end) - get_timestamp($date_start);
   
$seconds_one_year = get_days_per_year($date_start, $date_end) * 24 * 60 * 60;
   
$age = array();
   
$age['years_exact'] = $t_lived / $seconds_one_year;
   
$age['years'] = floor($t_lived / $seconds_one_year);
   
$seconds_remaining = $t_lived % $seconds_one_year;
   
$age['days'] = round($seconds_remaining / (24 * 60 * 60));
    return
$age;
}
function
get_timestamp($date) {
    list(
$y, $m, $d) = explode('-', $date);
    return
mktime(0, 0, 0, $m, $d, $y);
}
function
get_days_per_year($date_start, $date_end) {
    list(
$y1) = explode('-', $date_start);
    list(
$y2) = explode('-', $date_end);
   
$years_days = array();
    for(
$y = $y1; $y <= $y2; $y++) {
       
$years_days[] = date('L', mktime(0, 0, 0, 1, 1, $y)) ? 366 : 365;
    }
    return
round(array_sum($years_days) / count($years_days), 2);
}

$date_birth = '1979-10-12';
$date_now = date('Y-m-d');

$age = get_age($date_birth, $date_now);
echo
'<pre>';
print_r($age);
echo
'</pre>';
?>


It will display something like this:
Array
(
    [years_exact] => 28.972974329491
    [years] => 28
    [days] => 355
)
up
-11
mogster at redesign dot no
10 years ago
Just a simple function to return mktime from a db (mysql) datetime (Y-m-d H:i:s):

function retMktimest($dbdate) {
  return mktime(substr($dbdate, 11, 2), substr($dbdate, 14, 2), substr($dbdate, 17, 2), substr($dbdate, 5, 2), substr($dbdate, 8, 2), substr($dbdate, 0, 4));
}
up
-13
delfino dot salinas at gmail dot com
10 years ago
this function returns the number of days of a provided month and year, it consider the actual rules for leap years

(if the year is multiple of 4 which is not a multiple of 100 unless multiple of thousand then is a leap)
Regards, hope this function solves any issue :)

function daysinmonth($month,$year) {
$dim = 0;
switch ($month) {
    case 1:
    case 3:
    case 5:
    case 7:
    case 8:
    case 10:
    case 12:
        $dim=31;
        break;
    case 4:
    case 6:
    case 9:
    case 11:
        $dim=30;
        break;
    case 2:
        if($year%4==0) {
            if($year%100==0) {
                if($year%1000==0) { $dim=29; } else { $dim=28; }
            } else {
                $dim=29;
            }
        } else {$dim=28;}
        break;
    }
    return($dim);
}
To Top