Главная | Руководство по MySQL | MySQL Manual | Документация к HTTP серверу Apache | Apache HTTP Server Documentation | downloads | faq

искать  Язык: Английский


time

(PHP 4, PHP 5)

timeВозвращает текущую метку времени

Описание

int time ( void )

Возвращает количество секунд, прошедших с начала Эпохи Unix (The Unix Epoch, 1 января 1970, 00:00:00 GMT) до текущего времени.

См. также описание функций date() и microtime().


User Contributed Notes
time
alex nyoc net
24-Feb-2010 12:39
Here is a really simple hack used to calculate time difference between present and past and future (in a really efficient way!)

To change between past, present, future, you need to do things only on the display side (no code patch needed).

The default function is:
<?php
timeago
($referencedate=0, $timepointer='', $measureby='', $autotext=true)
?>

$timepointer is from where to start calculating and is only needed if you are calculating the difference between 2 specific times. In other words, the present is not one of those times.

$referencedate is the time you're calculating to. This is required for all calculations.

$measureby is the unit to use

$autotext is whether to add "days from now" or "ago" to the string. Option only for present dates, otherwise, this variable is set to off.

For a standard present-past, use: timeago(pastdate);

It will automatically detect the time since in the appropriate units.

There is some coding error because rounding plays a huge roll. If it's 390 days from now, instead of saying "1 year, 25 days", the function will say "1 year". Post a better solution if you can.

<?php
## alex at nyoc dot net
## Feel free to better for your needs

function timeago($referencedate=0, $timepointer='', $measureby='', $autotext=true){    ## Measureby can be: s, m, h, d, or y
   
if($timepointer == '') $timepointer = time();
   
$Raw = $timepointer-$referencedate;    ## Raw time difference
   
$Clean = abs($Raw);
   
$calcNum = array(array('s', 60), array('m', 60*60), array('h', 60*60*60), array('d', 60*60*60*24), array('y', 60*60*60*24*365));    ## Used for calculating
   
$calc = array('s' => array(1, 'second'), 'm' => array(60, 'minute'), 'h' => array(60*60, 'hour'), 'd' => array(60*60*24, 'day'), 'y' => array(60*60*24*365, 'year'));    ## Used for units and determining actual differences per unit (there probably is a more efficient way to do this)
   
   
if($measureby == ''){    ## Only use if nothing is referenced in the function parameters
       
$usemeasure = 's';    ## Default unit
   
       
for($i=0; $i<count($calcNum); $i++){    ## Loop through calcNum until we find a low enough unit
           
if($Clean <= $calcNum[$i][1]){        ## Checks to see if the Raw is less than the unit, uses calcNum b/c system is based on seconds being 60
               
$usemeasure = $calcNum[$i][0];    ## The if statement okayed the proposed unit, we will use this friendly key to output the time left
               
$i = count($calcNum);            ## Skip all other units by maxing out the current loop position
           
}       
        }
    }else{
       
$usemeasure = $measureby;                ## Used if a unit is provided
   
}
   
   
$datedifference = floor($Clean/$calc[$usemeasure][0]);    ## Rounded date difference
   
   
if($autotext==true && ($timepointer==time())){
        if(
$Raw < 0){
           
$prospect = ' from now';
        }else{
           
$prospect = ' ago';
        }
    }
   
    if(
$referencedate != 0){        ## Check to make sure a date in the past was supplied
       
if($datedifference == 1){    ## Checks for grammar (plural/singular)
           
return $datedifference . ' ' . $calc[$usemeasure][1] . ' ' . $prospect;
        }else{
            return
$datedifference . ' ' . $calc[$usemeasure][1] . 's ' . $prospect;
        }
    }else{
        return
'No input time referenced.';
    }
}
?>
nickr at visuality dot com
08-Feb-2010 09:54
Here is a version for the difference code that displays "ago" code.

It does use some precision after the time difference is longer than a day. ( ie days are more than 60 * 60 * 24 hours long )

<?php

   
function ago($datefrom,$dateto=-1)
    {
       
// Defaults and assume if 0 is passed in that
        // its an error rather than the epoch
   
       
if($datefrom==0) { return "A long time ago"; }
        if(
$dateto==-1) { $dateto = time(); }
       
       
// Make the entered date into Unix timestamp from MySQL datetime field

       
$datefrom = strtotime($datefrom);
   
       
// Calculate the difference in seconds betweeen
        // the two timestamps

       
$difference = $dateto - $datefrom;

       
// Based on the interval, determine the
        // number of units between the two dates
        // From this point on, you would be hard
        // pushed telling the difference between
        // this function and DateDiff. If the $datediff
        // returned is 1, be sure to return the singular
        // of the unit, e.g. 'day' rather 'days'
   
       
switch(true)
        {
           
// If difference is less than 60 seconds,
            // seconds is a good interval of choice
           
case(strtotime('-1 min', $dateto) < $datefrom):
               
$datediff = $difference;
               
$res = ($datediff==1) ? $datediff.' second ago' : $datediff.' seconds ago';
                break;
           
// If difference is between 60 seconds and
            // 60 minutes, minutes is a good interval
           
case(strtotime('-1 hour', $dateto) < $datefrom):
               
$datediff = floor($difference / 60);
               
$res = ($datediff==1) ? $datediff.' minute ago' : $datediff.' minutes ago';
                break;
           
// If difference is between 1 hour and 24 hours
            // hours is a good interval
           
case(strtotime('-1 day', $dateto) < $datefrom):
               
$datediff = floor($difference / 60 / 60);
               
$res = ($datediff==1) ? $datediff.' hour ago' : $datediff.' hours ago';
                break;
           
// If difference is between 1 day and 7 days
            // days is a good interval               
           
case(strtotime('-1 week', $dateto) < $datefrom):
               
$day_difference = 1;
                while (
strtotime('-'.$day_difference.' day', $dateto) >= $datefrom)
                {
                   
$day_difference++;
                }
               
               
$datediff = $day_difference;
               
$res = ($datediff==1) ? 'yesterday' : $datediff.' days ago';
                break;
           
// If difference is between 1 week and 30 days
            // weeks is a good interval           
           
case(strtotime('-1 month', $dateto) < $datefrom):
               
$week_difference = 1;
                while (
strtotime('-'.$week_difference.' week', $dateto) >= $datefrom)
                {
                   
$week_difference++;
                }
               
               
$datediff = $week_difference;
               
$res = ($datediff==1) ? 'last week' : $datediff.' weeks ago';
                break;           
           
// If difference is between 30 days and 365 days
            // months is a good interval, again, the same thing
            // applies, if the 29th February happens to exist
            // between your 2 dates, the function will return
            // the 'incorrect' value for a day
           
case(strtotime('-1 year', $dateto) < $datefrom):
               
$months_difference = 1;
                while (
strtotime('-'.$months_difference.' month', $dateto) >= $datefrom)
                {
                   
$months_difference++;
                }
               
               
$datediff = $months_difference;
               
$res = ($datediff==1) ? $datediff.' month ago' : $datediff.' months ago';

                break;
           
// If difference is greater than or equal to 365
            // days, return year. This will be incorrect if
            // for example, you call the function on the 28th April
            // 2008 passing in 29th April 2007. It will return
            // 1 year ago when in actual fact (yawn!) not quite
            // a year has gone by
           
case(strtotime('-1 year', $dateto) >= $datefrom):
               
$year_difference = 1;
                while (
strtotime('-'.$year_difference.' year', $dateto) >= $datefrom)
                {
                   
$year_difference++;
                }
               
               
$datediff = $year_difference;
               
$res = ($datediff==1) ? $datediff.' year ago' : $datediff.' years ago';
                break;
               
        }
        return
$res;

?>
andypsv at rcdrugs dot com
30-Jun-2009 06:43
RETURNS time left from supplied date ex. '3 days ago' etc. Basic function

<?php

function _ago($tm,$rcs = 0) {
   
$cur_tm = time(); $dif = $cur_tm-$tm;
   
$pds = array('second','minute','hour','day','week','month','year','decade');
   
$lngh = array(1,60,3600,86400,604800,2630880,31570560,315705600);
    for(
$v = sizeof($lngh)-1; ($v >= 0)&&(($no = $dif/$lngh[$v])<=1); $v--); if($v < 0) $v = 0; $_tm = $cur_tm-($dif%$lngh[$v]);
   
   
$no = floor($no); if($no <> 1) $pds[$v] .='s'; $x=sprintf("%d %s ",$no,$pds[$v]);
    if((
$rcs == 1)&&($v >= 1)&&(($cur_tm-$_tm) > 0)) $x .= time_ago($_tm);
    return
$x;
}

?>
yasmary at gmail dot com
06-Mar-2009 08:48
A time difference function that outputs the time passed in facebook's style: 1 day ago, or 4 months ago. I took andrew dot macrobert at gmail dot com function and tweaked it a bit. On a strict enviroment it was throwing errors, plus I needed it to calculate the difference in time between a past date and a future date.

<?php
function nicetime($date)
{
    if(empty(
$date)) {
        return
"No date provided";
    }
   
   
$periods         = array("second", "minute", "hour", "day", "week", "month", "year", "decade");
   
$lengths         = array("60","60","24","7","4.35","12","10");
   
   
$now             = time();
   
$unix_date         = strtotime($date);
   
      
// check validity of date
   
if(empty($unix_date)) {   
        return
"Bad date";
    }

   
// is it future date or past date
   
if($now > $unix_date) {   
       
$difference     = $now - $unix_date;
       
$tense         = "ago";
       
    } else {
       
$difference     = $unix_date - $now;
       
$tense         = "from now";
    }
   
    for(
$j = 0; $difference >= $lengths[$j] && $j < count($lengths)-1; $j++) {
       
$difference /= $lengths[$j];
    }
   
   
$difference = round($difference);
   
    if(
$difference != 1) {
       
$periods[$j].= "s";
    }
   
    return
"$difference $periods[$j] {$tense}";
}

$date = "2009-03-04 17:45";
$result = nicetime($date); // 2 days ago

?>
anon
27-Jan-2009 01:16
Below, a function to create TNG-style stardates, taking 2009 to start stardate 41000.0.  In fact, the offset is trivial to adjust if you wish to begin from a different date.

<?php
function getStardate(void)
{
 
$offset = 2000;
 
$seconds_per_stardate = 31449.6; // is the number of seconds in a year divided by 1000, for hopefully obvious reasons
 
return time() / $seconds_per_stardate + $offset;
}
?>

Other series use less reliable stardate formats, which makes it difficult [read: nigh impossible] to create a function that converts a unix timestamp into a stardate.
Anonymous
02-Sep-2008 12:30
A cleaner example (half the comparisons) of distanceOfTimeInWords() function below:

<?php
public static function distanceOfTimeInWords($fromTime, $toTime = 0, $showLessThanAMinute = false) {
   
$distanceInSeconds = round(abs($toTime - $fromTime));
   
$distanceInMinutes = round($distanceInSeconds / 60);
       
        if (
$distanceInMinutes <= 1 ) {
            if ( !
$showLessThanAMinute ) {
                return (
$distanceInMinutes == 0) ? 'less than a minute' : '1 minute';
            } else {
                if (
$distanceInSeconds < 5 ) {
                    return
'less than 5 seconds';
                }
                if (
$distanceInSeconds < 10 ) {
                    return
'less than 10 seconds';
                }
                if (
$distanceInSeconds < 20 ) {
                    return
'less than 20 seconds';
                }
                if (
$distanceInSeconds < 40 ) {
                    return
'about half a minute';
                }
                if (
$distanceInSeconds < 60 ) {
                    return
'less than a minute';
                }
               
                return
'1 minute';
            }
        }
        if (
$distanceInMinutes < 45 ) {
            return
$distanceInMinutes . ' minutes';
        }
        if (
$distanceInMinutes < 90 ) {
            return
'about 1 hour';
        }
        if (
$distanceInMinutes < 1440 ) {
            return
'about ' . round(floatval($distanceInMinutes) / 60.0) . ' hours';
        }
        if (
$distanceInMinutes < 2880 ) {
            return
'1 day';
        }
        if (
$distanceInMinutes < 43200 ) {
            return
'about ' . round(floatval($distanceInMinutes) / 1440) . ' days';
        }
        if (
$distanceInMinutes < 86400 ) {
            return
'about 1 month';
        }
        if (
$distanceInMinutes < 525600 ) {
            return
round(floatval($distanceInMinutes) / 43200) . ' months';
        }
        if (
$distanceInMinutes < 1051199 ) {
            return
'about 1 year';
        }
       
        return
'over ' . round(floatval($distanceInMinutes) / 525600) . ' years';
}
?>
Josh Abraham
28-Sep-2007 02:43
When dealing with the results of the time function, taking the modulus (remainder) is often a good way to find recurring information such as day of the week, week of the year, or month of the year. In the example given below of a firefighter's shift, you could do the following to simplify the code.

<?php

function whatShift() {

 
$referencePoint = mktime(7, 0, 0, 9, 11, 2004);   // Sept 11, 2004 at 7AM started an A Shift.

  //This is the where we divide the current time since reference by the amount of time in all shifts
  //The result of this is the remainder.
 
$sinceReference = (time() - $referencePoint) % (60 * 60 * 24 * 3);

 
//The rest of the code can be basically the same so I shortened it here.
 
if ($sinceReference < 60 * 60 * 25 $shift = "A";
  elseif (
$sinceReference < 60 * 60 * 49 $shift = "B";
  else
$shift = "C"

  return
$shift;

}

?>
jon at freilich dot com
21-Sep-2007 04:30
Fire Fighters typically work one day on and two days off.  Known as shifts and generally referred to as A, B and C.  I need to compute this for a web script so I came up with the following function.

Notes: You may need to change the reference date as not all departments are on the same rotation. Also, this does not take into account daylight savings time so the changeover moves by an hour.

<?php

function whatShift() {

 
$referencePoint = mktime(7, 0, 0, 9, 11, 2004);   // Sept 11, 2004 at 7AM started an A Shift.
 
$now = time();
 
 
// Next we need to know how many seconds since the start of the last A Shift.
  // First we compute how many 3 days cycles since the reference point then
  // subtract that number.
 
 
$difference = ($now - $referencePoint);
 
$cycles = floor($difference / (60 * 60 * 24 * 3));
 
$sinceReference = ($difference - ($cycles * 60 * 60 * 24 * 3));

  if (
$sinceReference < 60 * 60 * 25) {  // Before the start of the 25th hour it's A Shift.
   
$shift = "A";
    }
 
  elseif (
$sinceReference < 60 * 60 * 49) {  // Else before the start of the 49th hour it's B Shift.
   
$shift = "B";
    }
 
  else {
   
$shift = "C" // Else it's C Shift.
   
}

  return
$shift;

}

?>
by225 at yahoo dot com
06-Sep-2007 07:32
A function for converting to Unix time without using the MySQL UNIX_TIMESTAMP function in a query (MySQL allows eight different formats for timestamps):

<?php
function UnixTime($mysql_timestamp){
    if (
preg_match('/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/', $mysql_timestamp, $pieces)
        ||
preg_match('/(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/', $mysql_timestamp, $pieces)) {
           
$unix_time = mktime($pieces[4], $pieces[5], $pieces[6], $pieces[2], $pieces[3], $pieces[1]);
    } elseif (
preg_match('/\d{4}\-\d{2}\-\d{2} \d{2}:\d{2}:\d{2}/', $mysql_timestamp)
        ||
preg_match('/\d{2}\-\d{2}\-\d{2} \d{2}:\d{2}:\d{2}/', $mysql_timestamp)
        ||
preg_match('/\d{4}\-\d{2}\-\d{2}/', $mysql_timestamp)
        ||
preg_match('/\d{2}\-\d{2}\-\d{2}/', $mysql_timestamp)) {
           
$unix_time = strtotime($mysql_timestamp);
    } elseif (
preg_match('/(\d{4})(\d{2})(\d{2})/', $mysql_timestamp, $pieces)
        ||
preg_match('/(\d{2})(\d{2})(\d{2})/', $mysql_timestamp, $pieces)) {
           
$unix_time = mktime(0, 0, 0, $pieces[2], $pieces[3], $pieces[1]);
    }
  return
$unix_time;
}
?>
lsd25 at hotmail dot com
01-Sep-2007 02:53
I did an article on floating point time you can download from my website. Roun movements is the radial ounion movement and there is a quantum ounion movement as well, this code will generate the data for http://www.chronolabs.org.au/bin/roun-time-article.pdf which is an article on floating point time, I have created the calendar system as well for this time. It is compatible with other time and other solar systems with different revolutions of the planets as well as different quantumy stuff.

Thanks:

<?php
if ($gmt>0){
       
$gmt=-$gmt;
    } else {
       
$gmt=$gmt+$gmt+$gmt;
    }
   
   
$ptime = strtotime('2008-05-11 10:05 AM')+(60*60*gmt);
   
$weight = -20.22222222223+(1*gmt);

   
$roun_xa = ($tme)/(24*60*60);
   
$roun_ya = $ptime/(24*60*60);
   
$roun = (($roun_xa -$roun_ya) - $weight)+(microtime/999999);
   
   
$nonedeficient = array("seq1" => array(31,30,31,30,30,30,31,30,31,30,31,30),
                          
"seq2" => array(31,30,31,30,31,30,31,30,31,30,31,30),   
                          
"seq3" => array(31,30,31,30,30,30,31,30,31,30,31,30),
                          
"seq4" => array(31,30,31,30,30,30,31,30,31,30,31,30));

   
$deficient =     array("seq1" => array(31,30,31,30,30,30,31,30,31,30,31,30),
                          
"seq2" => array(31,30,31,30,31,30,31,30,31,30,31,30),   
                          
"seq3" => array(31,30,31,30,31,30,31,30,30,30,31,30),
                          
"seq4" => array(30,30,31,30,31,30,31,30,31,30,31,30));

   
$monthusage = isset($_GET['deficienty']) ? ${$_GET['deficienty']} : $deficient;
   
    foreach(
$monthusage as $key => $item){
       
$i++;
        foreach(
$item as $numdays){
           
$ttl_num=$ttl_num+$numdays;
        }
    }
   
   
$revolutionsperyear = $ttl_num / $i;
   
$numyears = round((round(ceil($roun)) / $revolutionsperyear),0);
   
   
$jtl = abs(abs($roun) - ceil($revolutionsperyear*($numyears+1)));
   
    while(
$month==0){
       
$day=0;
        foreach(
$monthusage as $key => $item){
           
$t++;
           
$u=0;
            foreach(
$item as $numdays){
                if (
$ii<abs($roun)){
                   
$isbelow=true;
                }
               
$ii=$ii+$numdays;
                if (
$ii>abs($roun)){
                   
$isabove=true;
                }
                if (
$isbelow==true&&$isabove==true){
                   
$daynum = floor(($ii-$numday)-abs($roun));
                   
$month = $u;
                   
$month++;
                   
$isbelow=false;
                   
$isabove=false;
                   
$nodaycount=true;
                }
                if (
$nodaycount==false)
                   
$day++;
               
$u++;
            }
        }
   
    }
   
   
$timer = substr($roun, strpos($roun,'.')+1,strlen($roun)-strpos($roun,'.')-1);
   
   
$roun_out= $numyears.'-'.$month.'-'.$daynum.' '.$day.".$timer";

?>
send at mail dot 2aj dot net
08-Jun-2006 06:58
If you want to create a "rounded" time stamp, for example, to the nearest 15 minutes use this as a reference:

<?php
$round_numerator
= 60 * 15 // 60 seconds per minute * 15 minutes equals 900 seconds
//$round_numerator = 60 * 60 or to the nearest hour
//$round_numerator = 60 * 60 * 24 or to the nearest day

// Calculate time to nearest 15 minutes!
$rounded_time = ( round ( time() / $round_numerator ) * $round_numerator );

//If it was 12:40 this would return the timestamp for 12:45;
//3:04, 3:00; etc.
?>
aidan at php dot net
08-Oct-2005 12:14
A simple function for calculating the number of seconds, minutes, etc in a timestamp is here:
http://aidanlister.com/2004/04/making-time-periods-readable/

Example:
<?php
echo time_duration(100000000);
// 3 years, 2 months, 19 hours, 22 minutes, 16 seconds

echo time_duration(100000000, null, true);
// 3 years, 2 months, 0 weeks, 0 days, 19 hours, 22 minutes, 16 seconds

echo time_duration(100000000, 'yMw');
// 3 years, 2 months

echo time_duration(100000000, 'd');
// 1157 days
?>


It is also worth noting:
* For manipulating arbitrary format, or length timestamps, see the PEAR::Date class.
http://pear.php.net/package/Date/
* PHP 6 will be shipping a new inbuilt date and timestamp manipulation API. It's available on PECL here:
http://pecl.php.net/package/datetime
mayank_arya at hotmail dot com
29-May-2003 01:13
Here's one way to generate all intermediate dates (in mySQL format) between any 2 dates.
Get start and end dates from user input, you'd need to do the basic validations that :
- start and end dates are valid dates
- start date <= end date.

<?php
//start date 2001-02-23
$sm=2;
$sd=23;
$sy=2001;

//end date 2001-03-14
$em=3;
$ed=14;
$ey=2001;

//utc of start and end dates
$s=mktime(0,0,0,$sm, $sd, $sy);
$e=mktime(0,0,0,$em, $ed, $ey);

while(
$s<=$e){
print
date('Y-m-d',$s)."< br >"; //display date in  mySQL format
$s=$s+86400; //increment date by 86400 seconds(1 day)
}

Hope this helps :)

?>
 

 
credits | contact