Delicious Bookmark this on Delicious Share on Facebook SlashdotSlashdot It! Digg! Digg



PHP : Function Reference : Date and Time Functions : time

time

Return current Unix timestamp (PHP 4, PHP 5)
int time ( )

Example 465. time() example

<?php
$nextWeek
= time() + (7 * 24 * 60 * 60);
                 
// 7 days; 24 hours; 60 mins; 60secs
echo 'Now:       '. date('Y-m-d') ."\n";
echo
'Next Week: '. date('Y-m-d', $nextWeek) ."\n";
// or using strtotime():
echo 'Next Week: '. date('Y-m-d', strtotime('+1 week')) ."\n";
?>

The above example will output something similar to:

Now:       2005-03-30
Next Week: 2005-04-06
Next Week: 2005-04-06

Related Examples ( Source code ) » time
















Code Examples / Notes » time

josh abraham

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


rspenc29

To further expand on shdowhawk's timeDiff function I added a small but important feature
function timeDiff($timestamp,$detailed=false,$n = 0){
   $now = time();
   #If the difference is positive "ago" - negative "away"
   ($timestamp >= $now) ? $action = 'away' : $action = 'ago';
   $diff = ($action == 'away' ? $timestamp - $now : $now - $timestamp);
   # Set the periods of time
   $periods = array("second", "minute", "hour", "day", "week", "month", "year", "decade");
   $lengths = array(1, 60, 3600, 86400, 604800, 2630880, 31570560, 315705600);
   # Go from decades backwards to seconds
   $i = sizeof($lengths) - 1;         # Size of the lengths / periods in case you change them
   $time = "";                        # The string we will hold our times in
   while($i >= $n) {
       if($diff > $lengths[$i-1]) {        # if the difference is greater than the length we are checking... continue
           $val = floor($diff / $lengths[$i-1]);    # 65 / 60 = 1.  That means one minute.  130 / 60 = 2. Two minutes.. etc
           $time .= $val ." ". $periods[$i-1].($val > 1 ? 's ' : ' ');  # The value, then the name associated, then add 's' if plural
           $diff -= ($val * $lengths[$i-1]);    # subtract the values we just used from the overall diff so we can find the rest of the information
           if(!$detailed) { $i = 0; }    # if detailed is turn off (default) only show the first set found, else show all information
       }
       $i--;
   }
 
   # Basic error checking.
   if($time == "") {
       return "Error-- Unable to calculate time.";
   } else {
       return $time.$action;
   }
}
Now you can specify where you want to stop. Example
timeDiff($yourtimestamp,1,4); //Stops after days (no hours, minutes, seconds)
timeDiff($yourtimestamp,1,5); //Stops after hours


08-sep-2000 08:42

To convert a MySQL timestamp to a Unix-style timestamp, use MySQL's UNIX_TIMESTAMP function.
For Example:
$result=mysql_query ("SELECT UNIX_TIMESTAMP(timestamp_column) as epoch_time FROM table");
$unix_timestamp = mysql_result ($result, 0, 0);


kobieta dot ryba

Time left function:
<?php
 define("TIME_PERIODS_PLURAL_SINGULAR", "weeks:week,years:year,days:day,hours:hour, : ,minutes:minute,seconds:second");
 DEFINE("TIME_LEFT_STRING_TPL", " #num# #period#");
 /**
  * @param $time  time stamp
 **/
 function time_left($time)
 {
     if (($now = time()) <= $time) return false;
     $timeRanges = array('years' => 365*60*60*24,/* 'weeks' => 60*60*24*7, */ 'days' => 60*60*24, 'hours' => 60*60, 'minutes' => 60, 'seconds' => 1);
     $secondsLeft = $now-$time;
     // prepare ranges
     $outRanges = array();
     foreach ($timeRanges as $period => $sec)
       if ($secondsLeft/$sec >= 1)
       {
         $outRanges[$period] =  floor($secondsLeft/$sec);
         $secondsLeft -= ($outRanges[$period] * $sec);
       }
     // playing with TIME_PERIODS_PLURAL_SINGULAR
     $periodsEx = explode(",", TIME_PERIODS_PLURAL_SINGULAR);
     $periodsAr = array();
     foreach ($periodsEx as $periods)
     {
       $ex  = explode(":", $periods);
       $periodsAr[$ex[0]] = array('plural' => $ex[0], 'singular' => $ex[1]);
     }
     // string out
     $outString = "";
     $outStringAr = array();
     foreach ($outRanges as $period => $num)
     {
       $per = $periodsAr[$period]['plural'];
       if ($num == 1)  $per = $periodsAr[$period]['singular'];
       $outString .= $outStringAr[$period] = str_replace(array("#num#", "#period#"), array($num, $per), TIME_LEFT_STRING_TPL);
     }
     return array('timeRanges' => $outRanges, 'leftStringAr' => $outStringAr, 'leftString' => $outString);
 }
 print_r(time_left(time()-60*60*24*365+59));
?>
Output:
Array
(
   [timeRanges] => Array
       (
           [days] => 364
           [hours] => 23
           [minutes] => 59
           [seconds] => 1
       )
   [leftStringAr] => Array
       (
           [days] =>  364 days
           [hours] =>  23 hours
           [minutes] =>  59 minutes
           [seconds] =>  1 second
       )
   [leftString] =>  364 days 23 hours 59 minutes 1 second
)


joncampell

Time difference both forward and backward, based on tristan's TimeAgo() function :)
function timeDiff($timestamp){
       $now = time();
       //If the difference is positive "ago" - negative "away"
       ($timestamp >= $now) ? $action = 'away' : $action = 'ago';
       switch($action) {
       case 'away':
               $diff = $timestamp - $now;
               break;
       case 'ago':
       default:
               // Determine the difference, between the time now and the timestamp
               $diff = $now - $timestamp;
               break;
       }
       // Set the periods of time
       $periods = array("second", "minute", "hour", "day", "week", "month", "year", "decade");
       // Set the number of seconds per period
       $lengths = array(1, 60, 3600, 86400, 604800, 2630880, 31570560, 315705600);
       // Go from decades backwards to seconds
       for ($val = sizeof($lengths) - 1; ($val >= 0) && (($number = $diff / $lengths[$val]) <= 1); $val--);
       // Ensure the script has found a match
       if ($val < 0) $val = 0;
       // Determine the minor value, to recurse through
       $new_time = $now - ($diff % $lengths[$val]);
       // Set the current value to be floored
       $number = floor($number);
       // If required create a plural
       if($number != 1) $periods[$val].= "s";
       // Return text
       $text = sprintf("%d %s ", $number, $periods[$val]);
       return $text . $action;
}
If anyone knows of an easier way to do this, please comment.


andrew dot macrobert

This function takes a timestamp and returns how long ago it was, in seconds, minutes, hours, days, or weeks (it will return it in minutes if it was >= than 60 seconds ago, hours if it was >= 60 minutes, etc.).
<?php
function ago($timestamp){
$difference = time() - $timestamp;
if($difference < 60)
return $difference." seconds ago";
else{
$difference = round($difference / 60);
if($difference < 60)
return $difference." minutes ago";
else{
$difference = round($difference / 60);
if($difference < 24)
return $difference." hours ago";
else{
$difference = round($difference / 24);
if($difference < 7)
return $difference." days ago";
else{
$difference = round($difference / 7);
return $difference." weeks ago";
}
}
}
}
}
?>


stardoggchamp

This function formate a timestamp into days, hours, minutes and seconds.
e.g the time until your birthday.
<?php
function formatetimestamp($until){
  $now = time();
  $difference = $until - $now;
  $days = floor($difference/86400);
  $difference = $difference - ($days*86400);
  $hours = floor($difference/3600);
  $difference = $difference - ($hours*3600);
  $minutes = floor($difference/60);
  $difference = $difference - ($minutes*60);
  $seconds = $difference;
  $output = "You have to wait $days Days, $hours Hours, $minutes Minutes and $seconds Seconds until this Day.";
  return $output;
}
//int mktime ( [int hour [, int minute [, int second [, int month [, int day [, int year [, int is_dst]]]]]]] )
echo formatetimestamp(mktime(0,0,0,12,31,2006)); //output: e.g "You have to wait 162 Days, 4 Hours, 38 Minutes and 46 Seconds until this Day"
?>


stack-phpnotes

My modification and enhancements to the timeDiff() function last updated by sean sullivan. The rewrite was done to add a couple new optional parameters but I also got a bump in performance. On a completely personal preference level I changed the month and year second values with ones I got from Google searches.
Written and tested with 5.2.0.
Options include
to = time(); date to compute the range to
parts = 1; number of parts to display max
precision = 'second'; lowest part to compute to
distance = TRUE; include the 'ago' or 'away' bit
separator = ', '; separates the parts
<?php
function timeDiff($time, $opt = array()) {
// The default values
$defOptions = array(
'to' => 0,
'parts' => 1,
'precision' => 'second',
'distance' => TRUE,
'separator' => ', '
);
$opt = array_merge($defOptions, $opt);
// Default to current time if no to point is given
(!$opt['to']) && ($opt['to'] = time());
// Init an empty string
$str = '';
// To or From computation
$diff = ($opt['to'] > $time) ? $opt['to']-$time : $time-$opt['to'];
// An array of label => periods of seconds;
$periods = array(
'decade' => 315569260,
'year' => 31556926,
'month' => 2629744,
'week' => 604800,
'day' => 86400,
'hour' => 3600,
'minute' => 60,
'second' => 1
);
// Round to precision
if ($opt['precision'] != 'second')
$diff = round(($diff/$periods[$opt['precision']])) * $periods[$opt['precision']];
// Report the value is 'less than 1 ' precision period away
(0 == $diff) && ($str = 'less than 1 '.$opt['precision']);
// Loop over each period
foreach ($periods as $label => $value) {
// Stitch together the time difference string
(($x=floor($diff/$value))&&$opt['parts']--) && $str.=($str?$opt['separator']:'').($x.' '.$label.($x>1?'s':''));
// Stop processing if no more parts are going to be reported.
if ($opt['parts'] == 0 || $label == $opt['precision']) break;
// Get ready for the next pass
$diff -= $x*$value;
}
$opt['distance'] && $str.=($str&&$opt['to']>$time)?' ago':' away';
return $str;
}
?>
Usage:
$span = timeDiff($when);
or
$span = timeDiff($when, array('parts' => 3));


matt

Lots of MySQL traffic, little PostgreSQL.  PG hasn't UNIX_TIMESTAMP()- instead, use:
extract(epoch from ____)
As in:
SELECT extract(epoch from mytimestamp) FROM mytable WHERE mycondition = true;


jh2000

Just a small notice:
use the time() function instead of date("U"), it is much faster (about 1000 times~)


tristan

Initially I was using Andrew's function to convert a timestamp into a formatted age. It has issues with times greater than a day (div by 0). I also added recursion to produce a result similar to "2 decades 6 months 3 weeks 2 days 6 hours 56 minutes 52 seconds" when input a timestamp from 1986. Hopefully someone will find this useful.
<?php
public static function TimeAgo($timestamp){

// Store the current time
$current_time = time();

// Determine the difference, between the time now and the timestamp
$difference = $current_time - $timestamp;

// Set the periods of time
$periods = array("second", "minute", "hour", "day", "week", "month", "year", "decade");

// Set the number of seconds per period
$lengths = array(1, 60, 3600, 86400, 604800, 2630880, 31570560, 315705600);
// Determine which period we should use, based on the number of seconds lapsed.
// If the difference divided by the seconds is more than 1, we use that. Eg 1 year / 1 decade = 0.1, so we move on
// Go from decades backwards to seconds
for ($val = sizeof($lengths) - 1; ($val >= 0) && (($number = $difference / $lengths[$val]) <= 1); $val--);
// Ensure the script has found a match
if ($val < 0) $val = 0;

// Determine the minor value, to recurse through
$new_time = $current_time - ($difference % $lengths[$val]);

// Set the current value to be floored
$number = floor($number);

// If required create a plural
if($number != 1) $periods[$val].= "s";

// Return text
$text = sprintf("%d %s ", $number, $periods[$val]);
// Ensure there is still something to recurse through, and we have not found 1 minute and 0 seconds.
if (($val >= 1) && (($current_time - $new_time) > 0)){
$text .= self::TimeAgo($new_time);
}

return $text;
}
?>


sunjith

In ron's script, the while loop condition should be ($i >0). Otherwise, the index $lengths goes to -1 which will show an error.

info

in order to get the timestamp of the beginning of the current day (useful for synchronising) just do this:
$time = time();
$start_time = mktime(0, 0, 0, date('m', $time),date('d', $time),date('Y', $time));


webmaster

In a recent object I had to calculate the time difference between timestamps in a string format, so I wrote this nice little function I'd like to share.
<?php
define('INT_SECOND', 1);
define('INT_MINUTE', 60);
define('INT_HOUR', 3600);
define('INT_DAY', 86400);
define('INT_WEEK', 604800);
function get_formatted_timediff($then, $now = false)
{
   $now      = (!$now) ? time() : $now;
   $timediff = ($now - $then);
   $weeks    = (int) intval($timediff / INT_WEEK);
   $timediff = (int) intval($timediff - (INT_WEEK * $weeks));
   $days     = (int) intval($timediff / INT_DAY);
   $timediff = (int) intval($timediff - (INT_DAY * $days));
   $hours    = (int) intval($timediff / INT_HOUR);
   $timediff = (int) intval($timediff - (INT_HOUR * $hours));
   $mins     = (int) intval($timediff / INT_MINUTE);
   $timediff = (int) intval($timediff - (INT_MINUTE * $mins));
   $sec      = (int) intval($timediff / INT_SECOND);
   $timediff = (int) intval($timediff - ($sec * INT_SECOND));
   $str = '';
   if ( $weeks )
   {
       $str .= intval($weeks);
       $str .= ($weeks > 1) ? ' weeks' : ' week';
   }
   if ( $days )
   {
       $str .= ($str) ? ', ' : '';
       $str .= intval($days);
       $str .= ($days > 1) ? ' days' : ' day';
   }
   if ( $hours )
   {
       $str .= ($str) ? ', ' : '';
       $str .= intval($hours);
       $str .= ($hours > 1) ? ' hours' : ' hour';
   }
   if ( $mins )
   {
       $str .= ($str) ? ', ' : '';
       $str .= intval($mins);
       $str .= ($mins > 1) ? ' minutes' : ' minute';
   }
   if ( $sec )
   {
       $str .= ($str) ? ', ' : '';
       $str .= intval($sec);
       $str .= ($sec > 1) ? ' seconds' : ' second';
   }
   
   if ( !$weeks && !$days && !$hours && !$mins && !$sec )
   {
$str .= '0 seconds ago';
   }
   else
   {
$str .= ' ago';
   }
   
   return $str;
}
?>


ron

Improvement on top of shdowhawk at gmail dot com:
1. Calculate the time difference (from start to end)
2. Time can be provided as formatted (e.g. 2005-04-02 12:11:10) or integer (12233455).
3. Provide a short display, e.g. 12h 3m 23s
if (!function_exists('timeDiff')){
function timeDiff($starttime, $endtime, $detailed=false, $short = true){
if(! is_int($starttime)) $starttime = strtotime($starttime);
if(! is_int($endtime)) $endtime = strtotime($endtime);

$diff = ($starttime >= $endtime ? $starttime - $endtime : $endtime - $starttime);

# Set the periods of time
$periods = array("second", "minute", "hour", "day", "week", "month", "year", "decade");
$lengths = array(1, 60, 3600, 86400, 604800, 2630880, 31570560, 315705600);

if($short){
$periods = array("s", "m", "h", "d", "m", "y");
$lengths = array(1, 60, 3600, 86400, 2630880, 31570560);
}

# Go from decades backwards to seconds
$i = sizeof($lengths) - 1; # Size of the lengths / periods in case you change them
$time = ""; # The string we will hold our times in
while($i >= 0) {
if($diff > $lengths[$i-1]) { # if the difference is greater than the length we are checking... continue
$val = floor($diff / $lengths[$i-1]);    # 65 / 60 = 1.  That means one minute.  130 / 60 = 2. Two minutes.. etc
$time .= $val . ($short ? '' : ' ') . $periods[$i-1] . ((!$short && $val > 1) ? 's ' : ' ');  # The value, then the name associated, then add 's' if plural
$diff -= ($val * $lengths[$i-1]);    # subtract the values we just used from the overall diff so we can find the rest of the information
if(!$detailed) { $i = 0; }    # if detailed is turn off (default) only show the first set found, else show all information
}
$i--;
}
 
return $time;
}
}


send

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.
?>


shdowhawk

I modified the timeDiff scripts from what other people just wrote.  I added my little twist onto it =)
Basically... now you can add in a detailed option.  By default it is turned off, so we get the .. 1 hour ago  .. or .. 2 weeks away.
By calling timeDiff($timestamp,1) ... or timeDiff($timeStamp,true) .. we can now get a detailed count down.  Ex: 1 hour 7 minutes 47 seconds ago
function timeDiff($timestamp,$detailed=false){
$now = time();
#If the difference is positive "ago" - negative "away"
($timestamp >= $now) ? $action = 'away' : $action = 'ago';
$diff = ($action == 'away' ? $timestamp - $now : $now - $timestamp);
# Set the periods of time
$periods = array("second", "minute", "hour", "day", "week", "month", "year", "decade");
$lengths = array(1, 60, 3600, 86400, 604800, 2630880, 31570560, 315705600);
# Go from decades backwards to seconds
$i = sizeof($lengths) - 1; # Size of the lengths / periods in case you change them
$time = ""; # The string we will hold our times in
while($i >= 0) {
if($diff > $lengths[$i-1]) { # if the difference is greater than the length we are checking... continue
$val = floor($diff / $lengths[$i-1]); # 65 / 60 = 1.  That means one minute.  130 / 60 = 2. Two minutes.. etc
$time .= $val ." ". $periods[$i-1].($val > 1 ? 's ' : ' ');  # The value, then the name associated, then add 's' if plural
$diff -= ($val * $lengths[$i-1]); # subtract the values we just used from the overall diff so we can find the rest of the information
if(!$detailed) { $i = 0; } # if detailed is turn off (default) only show the first set found, else show all information
}
$i--;
}

# Basic error checking.
if($time == "") {
return "Error-- Unable to calculate time.";
} else {
return $time.$action;
}
}


greg

I found Craig's code useful, but wanted the ability to limit the granularity to only show most significant time periods. there's the bit i adapted:
<?
function ago ( $epoch, $max_phrases=null ) {
 $duration  = time() - $epoch;
 return seconds2human( $duration > 0 ? $duration : 0,
                       $max_phrases) . " ago";
}
function seconds2human($epoch, $max_phrases=null ){
 // kindly adapted from Craig Francis at http://www.php.net/manual/en/function.time.php#74652
 //--------------------------------------------------
 // Maths
 $sec = $epoch % 60;
 $epoch -= $sec;
 $minSeconds = $epoch % 3600;
 $epoch -= $minSeconds;
 $min = ($minSeconds / 60);
 $hourSeconds = $epoch % 86400;
 $epoch -= $hourSeconds;
 $hour = ($hourSeconds / 3600);
 $daySeconds = $epoch % 604800;
 $epoch -= $daySeconds;
 $day = ($daySeconds / 86400);
 $week = ($epoch / 604800);
 //--------------------------------------------------
 // Text
 $output = array();
 if ($week > 0) {
   $output[] = $week . ' week' . ($week != 1 ? 's' : '');
 }
 if ($day > 0) {
   $output[] = $day . ' day' . ($day != 1 ? 's' : '');
 }
 if ($hour > 0) {
   $output[] = $hour . ' hour' . ($hour != 1 ? 's' : '');
 }
 if ($min > 0) {
   $output[] = $min . ' minute' . ($min != 1 ? 's' : '');
 }
 if ($sec > 0 || $output == '') {
   $output[] = $sec . ' second' . ($sec != 1 ? 's' : '');
 }
 //--------------------------------------------------
 // Grammar
 if( isset($max_phrases) )
   $output = array_slice($output, 0, $max_phrases);
 $return = join( ', ', $output);
 $return = preg_replace('/, ([^,]+)$/', ' and $1', $return);
 //--------------------------------------------------
 // Return the output
 return $return;
}
?>


lsd25

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:
<?
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";
?>


emory dot smith

heres another way to convert a mysql timestamp to a unix timestamp without using the function UNIX_TIMESTAMP in mysql:
<?php
$unix_timestamp = strtotime($mysql_timestamp);
?>


mayank_arya

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


jason

Here you go. You can specify how much you wanna see -- years, weeks, days, hours, minutes or seconds. Returns an Array containing a String along with the individual time values.
Usage:
array calc_tl( int $unixTime, [int $unixTime], [char $selector] )
<?php
function calc_tl($t, $sT = 0, $sel = 'Y') {
$sY = 31536000;
$sW = 604800;
$sD = 86400;
$sH = 3600;
$sM = 60;
if($sT) {
$t = ($sT - $t);
}
if($t <= 0) {
$t = 0;
}
$bs[1] = ('1'^'9'); /* Backspace */
switch(strtolower($sel)) {
case 'y':
$y = ((int)($t / $sY));
$t = ($t - ($y * $sY));
$r['string'] .= "{$y} years{$bs[$y]} ";
$r['years'] = $y;
case 'w':
$w = ((int)($t / $sW));
$t = ($t - ($w * $sW));
$r['string'] .= "{$w} weeks{$bs[$w]} ";
$r['weeks'] = $w;
case 'd':
$d = ((int)($t / $sD));
$t = ($t - ($d * $sD));
$r['string'] .= "{$d} days{$bs[$d]} ";
$r['days'] = $d;
case 'h':
$h = ((int)($t / $sH));
$t = ($t - ($h * $sH));
$r['string'] .= "{$h} hours{$bs[$h]} ";
$r['hours'] = $h;
case 'm':
$m = ((int)($t / $sM));
$t = ($t - ($m * $sM));
$r['string'] .= "{$m} minutes{$bs[$m]} ";
$r['minutes'] = $m;
case 's':
$s = $t;
$r['string'] .= "{$s} seconds{$bs[$s]} ";
$r['seconds'] = $s;
break;
default:
return calc_tl($t);
break;
}
return $r;
}
// A few exaggerated examples:
$startTime = time();
$stopTime  = mktime(23,59,59,12,31,2011);
$tY = calc_tl($startTime, $stopTime, 'Y'); // Years (default)
$tD = calc_tl($startTime, $stopTime, 'D'); // Days
$tH = calc_tl($startTime, $stopTime, 'H'); // Hours
print_r($tY);
print_r($tD);
print_r($tH);
?>
OUTPUT
Array
(
[string] => 4 years 35 weeks 6 days 4 hours 54 minutes 33 seconds
[years] => 4
[weeks] => 35
[days] => 6
[hours] => 4
[minutes] => 54
[seconds] => 33
)
Array
(
[string] => 1711 days 4 hours 54 minutes 33 seconds
[days] => 1711
[hours] => 4
[minutes] => 54
[seconds] => 33
)
Array
(
[string] => 41068 hours 54 minutes 33 seconds
[hours] => 41068
[minutes] => 54
[seconds] => 33
)


sean sullivan

Fixed divide by zero warnings given by the timeDiff function.  The change is that the for loop doesn't count down to 0 anymore, just 1.  I dont think it has any side effects.
# max_detail_levels - how deep to go down? If max_detail_levels is set to 2, text will output something like "3 days 4 hours" instead of "3 days 4 hours 10 minutes 55 seconds"
# precision_level - this is what rspenc29 was trying to accomplish. If you want to only report a minimum value of say 1 hour, then you should set this to "hour"
function timeDiff($timestamp,$detailed=false, $max_detail_levels=8, $precision_level='second'){
   $now = time();
   #If the difference is positive "ago" - negative "away"
   ($timestamp >= $now) ? $action = 'away' : $action = 'ago';
 
   # Set the periods of time
   $periods = array("second", "minute", "hour", "day", "week", "month", "year", "decade");
   $lengths = array(1, 60, 3600, 86400, 604800, 2630880, 31570560, 315705600);
   $diff = ($action == 'away' ? $timestamp - $now : $now - $timestamp);
 
   $prec_key = array_search($precision_level,$periods);
 
   # round diff to the precision_level
   $diff = round(($diff/$lengths[$prec_key]))*$lengths[$prec_key];
 
   # if the diff is very small, display for ex "just seconds ago"
   if ($diff <= 10) {
       $periodago = max(0,$prec_key-1);
       $agotxt = $periods[$periodago].'s';
       return "just $agotxt $action";
   }
 
   # Go from decades backwards to seconds
   $time = "";
   for ($i = (sizeof($lengths) - 1); $i>0; $i--) {
       if($diff > $lengths[$i-1] && ($max_detail_levels > 0)) {        # if the difference is greater than the length we are checking... continue
           $val = floor($diff / $lengths[$i-1]);    # 65 / 60 = 1.  That means one minute.  130 / 60 = 2. Two minutes.. etc
           $time .= $val ." ". $periods[$i-1].($val > 1 ? 's ' : ' ');  # The value, then the name associated, then add 's' if plural
           $diff -= ($val * $lengths[$i-1]);    # subtract the values we just used from the overall diff so we can find the rest of the information
           if(!$detailed) { $i = 0; }    # if detailed is turn off (default) only show the first set found, else show all information
           $max_detail_levels--;
       }
   }

   # Basic error checking.
   if($time == "") {
       return "Error-- Unable to calculate time.";
   } else {
       return $time.$action;
   }
}


jon

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


john

did a quick test comparing time() with date("U"), using 100,000 iterations. Granted, I did this on a 2.4GHz Celeron... the results should still stand.
time() (100000) : 0.0589900016785
date("U") (100000) : 22.246557951


nimit dot maru

Correcting some problems with rspenc29's addition, and adding another feature:
# max_detail_levels - how deep to go down? If max_detail_levels is set to 2, text will output something like "3 days 4 hours" instead of "3 days 4 hours 10 minutes 55 seconds"
# precision_level - this is what rspenc29 was trying to accomplish. If you want to only report a minimum value of say 1 hour, then you should set this to "hour"
function timeDiff($timestamp,$detailed=false, $max_detail_levels=8, $precision_level='second'){
   $now = time();
   #If the difference is positive "ago" - negative "away"
   ($timestamp >= $now) ? $action = 'away' : $action = 'ago';

   # Set the periods of time
   $periods = array("second", "minute", "hour", "day", "week", "month", "year", "decade");
   $lengths = array(1, 60, 3600, 86400, 604800, 2630880, 31570560, 315705600);
   $diff = ($action == 'away' ? $timestamp - $now : $now - $timestamp);

$prec_key = array_search($precision_level,$periods);

# round diff to the precision_level
$diff = round(($diff/$lengths[$prec_key]))*$lengths[$prec_key];

   # if the diff is very small, display for ex "just seconds ago"
if ($diff <= 10) {
$periodago = max(0,$prec_key-1);
$agotxt = $periods[$periodago].'s';
       return "just $agotxt $action";
   }
   
   # Go from decades backwards to seconds
   $time = "";
for ($i = (sizeof($lengths) - 1); $i>=0; $i--) {
       if($diff > $lengths[$i-1] && ($max_detail_levels > 0)) {        # if the difference is greater than the length we are checking... continue
           $val = floor($diff / $lengths[$i-1]);    # 65 / 60 = 1.  That means one minute.  130 / 60 = 2. Two minutes.. etc
           $time .= $val ." ". $periods[$i-1].($val > 1 ? 's ' : ' ');  # The value, then the name associated, then add 's' if plural
           $diff -= ($val * $lengths[$i-1]);    # subtract the values we just used from the overall diff so we can find the rest of the information
           if(!$detailed) { $i = 0; }    # if detailed is turn off (default) only show the first set found, else show all information
       $max_detail_levels--;
       }
   }
 
   # Basic error checking.
   if($time == "") {
       return "Error-- Unable to calculate time.";
   } else {
       return $time.$action;
   }
}


paul

Be careful about using the database clock (say UNIX_TIMESTAMP() in MySQL) and the time() function if you're writing an application that may have the database be on a different machine than the web server.  In that situation,  applications can break because of clock skew -- use a single authority for timestamps if possible.

andrew dot macrobert

An improved version of my previous function:
<?
 function ago($timestamp){
   $difference = time() - $timestamp;
   $periods = array("second", "minute", "hour", "day", "week", "month", "years", "decade");
   $lengths = array("60","60","24","7","4.35","12","10");
   for($j = 0; $difference >= $lengths[$j]; $j++)
     $difference /= $lengths[$j];
   $difference = round($difference);
   if($difference != 1) $periods[$j].= "s";
   $text = "$difference $periods[$j] ago";
   return $text;
 }
?>


by225

A function for converting to Unix time without using the MySQL UNIX_TIMESTAMP function in a query (MySQL allows eight different formats for timestamps):
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;
}


aidan

* A simple function for calculating the number of seconds, minutes, etc in a timestamp is here:
http://aidanlister.com/repos/v/Duration.php
Example:
<?php
$time = 60*60*2 + 20*60 + 5;
// Gives 2 hours, 20 minutes, 5 seconds
echo Duration::toString($time);
?>
* 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


krisdover

# a simple html/php formatted calendar which returns
# the date as a unix timestamp when the required day
# is selected. Also allows for setting of time in 24hr format
# kris dover, 2006-09-09
<?php
 $sel_date = isset($_REQUEST['sel_date']) ? $_REQUEST['sel_date'] : time();
 if( isset($_POST['hrs']) ){
$t = getdate($sel_date);
$sel_date = mktime($_POST['hrs'], $_POST['mins'], $t['seconds'], $t['mon'], $t['mday'], $t['year']);
 }
 $t = getdate($sel_date);
 $start_date = mktime($t['hours'], $t['minutes'], $t['seconds'], $t['mon'], 1, $t['year']);
 $start_date -= 86400 * date('w', $start_date);
 
 $prev_year = mktime($t['hours'], $t['minutes'], $t['seconds'], $t['mon'], $t['mday'], $t['year'] - 1);
 $prev_month = mktime($t['hours'], $t['minutes'], $t['seconds'], $t['mon'] - 1, $t['mday'], $t['year']);
 $next_year = mktime($t['hours'], $t['minutes'], $t['seconds'], $t['mon'], $t['mday'], $t['year'] + 1);
 $next_month = mktime($t['hours'], $t['minutes'], $t['seconds'], $t['mon'] + 1, $t['mday'], $t['year']);
?>
<form method="post">
<table width="180" border="0" cellspacing="1"
 style="border: 1px solid black; font-family: Verdana, Arial, Helvetica, sans-serif; font-size: x-small; text-align: center">
 <tr>
   <td width="14%" bgcolor="#66FF99">
  <a href="?sel_date=<?= $prev_year ?>" style="text-decoration: none" title="Prevous Year">&lt;&lt;</a></td>
   <td width="14%" bgcolor="#66FF99">
  <a href="?sel_date=<?= $prev_month ?>" style="text-decoration: none" title="Prevous Month">&lt;</a></td>
   <td colspan="3" bgcolor="#66FF99">
      <?= date('M Y', $sel_date) ?>
   </td>
   <td width="14%" bgcolor="#66FF99">
  <a href="?sel_date=<?= $next_month ?>" style="text-decoration: none" title="Next Month">&gt;</a></td>
   <td width="14%" bgcolor="#66FF99">
  <a href="?sel_date=<?= $next_year ?>" style="text-decoration: none" title="Next Year">&gt;&gt;</a></td>
 </tr>
 <tr>
   <td bgcolor="#0099FF">Sun</td>
   <td bgcolor="#0099FF">Mon</td>
   <td width="14%" bgcolor="#0099FF">Tue</td>
   <td width="14%" bgcolor="#0099FF">Wed</td>
   <td width="14%" bgcolor="#0099FF">Thu</td>
   <td bgcolor="#0099FF">Fri</td>
   <td bgcolor="#0099FF">Sat</td>
 </tr>
 <?php
    $day = 1;
    for($i = $start_date; $day <= 42; $i+=86400, $day++){
if( $day % 7 == 1 ) echo "<tr>\n";
if( $t['mon'] == date('n', $i ) )
  if( $i == $sel_date )
     echo ' <td bgcolor="gold">'. date('j', $i) ."</td>\n";
  else
         echo ' <td><a href="?sel_date='. $i .'" style="text-decoration: none">'. date('j', $i) ."</a></td>\n";
else
  echo ' <td ><a href="?sel_date='. $i .'" style="text-decoration: none"><font  color="silver">'. date('j', $i) ."</font></a></td>\n";
if( $day % 7 == 0 )  echo "</tr>\n";
}
 ?>
 <tr>
   <td colspan="7" align="left" bgcolor="silver">Time:
<select name="hrs" onchange="document.forms[0].submit()">
<?php
  for($i = 0; $i < 24; $i++)
     echo '   <option '. (date('G', $sel_date)==$i ? 'selected':'') .'>'. sprintf('%02d', $i) ."</option>\n";
?>
</select>:
<select name="mins" onchange="document.forms[0].submit()">
<?php
   for($i = 0; $i < 60; $i++)
  echo '   <option '. (date('i', $sel_date)==$i ? 'selected':'') .'>'. sprintf('%02d', $i) ."</option>\n";
?>
</select> hrs
<input type="hidden" name="sel_date" value="<?= $sel_date ?>">
</td>
 </tr>
</table>
</form>


Change Language


Follow Navioo On Twitter
checkdate
date_create
date_date_set
date_default_timezone_get
date_default_timezone_set
date_format
date_isodate_set
date_modify
date_offset_get
date_parse
date_sun_info
date_sunrise
date_sunset
date_time_set
date_timezone_get
date_timezone_set
date
getdate
gettimeofday
gmdate
gmmktime
gmstrftime
idate
localtime
microtime
mktime
strftime
strptime
strtotime
time
timezone_abbreviations_list
timezone_identifiers_list
timezone_name_from_abbr
timezone_name_get
timezone_offset_get
timezone_open
timezone_transitions_get
eXTReMe Tracker