©
이 문서에서는 PHP 중국어 웹사이트 매뉴얼 풀어 주다
(PHP 4, PHP 5, PHP 7)
time — 返回当前的 Unix 时间戳
返回自从 Unix 纪元(格林威治时间 1970 年 1 月 1 日 00:00:00)到当前时间的秒数。
Example #1 time() 例子
<?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" ;
?>
以上例程的输出类似于:
Now: 2005-03-30 Next Week: 2005-04-06 Next Week: 2005-04-06
自 PHP 5.1 起在 $_SERVER['REQUEST_TIME'] 中保存了发起该请求时刻的时间戳。
[#1] Peter F [2015-06-04 12:58:59]
Javier:
The issue are highlighting is with the date() function, not with time(). the following code demonstrates this:
<?php
// server in BST Timezone
print 'server timezone<br>';
$time1 = date('H:i:s', time() - date('Z')); // 12:50:29
$time2 = date('H:i:s', gmdate('U')); // 13:50:29
$time3 = date('H:i:s', time()); // 13:50:29
$time4 = time() - date('Z'); // 1433418629
$time5 = gmdate('U'); // 1433422229
$time6 = time(); // 1433422229
print $time1.'<br>';
print $time2.'<br>';
print $time3.'<br>';
print $time4.'<br>';
print $time5.'<br>';
print $time6.'<br>';
ini_set('date.timezone', 'Europe/Berlin');
print 'Europe/Berlin<br>';
$time1 = date('H:i:s', time() - date('Z')); // 12:50:29
$time2 = date('H:i:s', gmdate('U')); // 14:50:29
$time3 = date('H:i:s', time()); // 14:50:29
$time4 = time() - date('Z'); // 1433415029
$time5 = gmdate('U'); // 1433422229
$time6 = time(); // 1433422229
print $time1.'<br>';
print $time2.'<br>';
print $time3.'<br>';
print $time4.'<br>';
print $time5.'<br>';
print $time6.'<br>';
ini_set('date.timezone', 'UTC');
print 'UTC<br>';
$time1 = date('H:i:s', time() - date('Z')); // 12:50:29
$time2 = date('H:i:s', gmdate('U')); // 12:50:29
$time3 = date('H:i:s', time()); // 12:50:29
$time4 = time() - date('Z'); // 1433422229
$time5 = gmdate('U'); // 1433422229
$time6 = time(); // 1433422229
print $time1.'<br>';
print $time2.'<br>';
print $time3.'<br>';
print $time4.'<br>';
print $time5.'<br>';
print $time6.'<br>';
?>
[#2] javier [2015-05-10 10:47:15]
I think the documentation regarding PHP time-related functions and time zones is a bit confusing.
Let's suppose we live in Berlin, which has time zone "Europe/Berlin" and it's UTC+1 in winter and UTC+2 in summer. This means that for 10:00 UTC+0, the local time in Berlin is 11:00 in winter and 12:00 in summer.
The results using different methods to get the timestamp are:
<?php
ini_set('date.timezone', 'Europe/Berlin');
$time1 = date('H:i:s', time() - date('Z')); // 10:00:00
$time2 = date('H:i:s', gmdate('U')); // 12:00:00
$time3 = date('H:i:s', time()); // 12:00:00
ini_set('date.timezone', 'UTC');
$time4 = date('H:i:s', time() - date('Z')); // 10:00:00
$time5 = date('H:i:s', gmdate('U')); // 10:00:00
$time6 = date('H:i:s', time()); // 10:00:00
?>
So, if you want to ensure UTC+0 timestamp in any environment, use this:
<?php
$timestamp = time() - date('Z');
?>
The other methods, including time(), will produce different results depending on the value of 'date.timezone'. This is extremely important if you have multiple servers across different countries, and you want to run all of them using UTC+0 without worrying about the particular time zone in which the server is located. The alternative, of course, is calling ini_set('date.timezone', 'UTC'); at the very beginning.
[#3] hoangvu4000 at gmail dot com [2014-04-11 05:53:27]
//Calculate number of hours between pass and now
$dayinpass = "2013-06-23 05:09:12";
$today = time();
$dayinpass= strtotime($dayinpass);
echo round(abs($today-$dayinpass)/60/60);
//Calculate number of days between pass and now
$dayinpass = "2013-06-23 05:09:12";
$today = time();
$dayinpass= strtotime($dayinpass);
echo round(abs($today-$dayinpass)/60/60/24);
[#4] jnostuh at gmail dot com [2013-10-18 13:52:18]
I built this function to get the strtotime numbers for the beginning and ending of the month and return them as arrays in an object. Cheers.
//Returns values in the format of strtotime for evaluating purposes!
function returnDateFirstAndLast($numberOfMonths) {
$time=time();
$lastdayofcurrentmonth=strtotime('+1 month -1 day',strtotime(date('Y-m-1 24:59:59',$time)));
$values=new stdClass();
for ( $i = 0;$i < $numberOfMonths;$i++ ) {
$time=time();
$firstdayofmonth=strtotime('-'.$i.' month',strtotime(date('Y-m-1 00:00:00',$time)));
$lastdayofmonth=strtotime('-'.($i - 1).' month -1 day',strtotime(date('Y-m-1 24:59:59',$time)));
$first[$i]=$firstdayofmonth;
if ( $i == 0 ) {
$last[$i]=$lastdayofcurrentmonth;
} else {
$last[$i]=$lastdayofmonth;
}
}
$values->first=$first;
$values->last=$last;
return $values;
}
[#5] Anonymous [2013-05-15 07:46:13]
The documentation says 'Return current Unix timestamp'. The definition itself of the unix time shows that it is independent of the timezone so it is obvious that this function will return the same value for the different timezones.
[#6] w dot scholtyssek at netdivision dot eu [2013-04-26 11:47:49]
public static function daysBetween($date_1, $date_2) {
$one_day = 1000 * 60 * 60 * 24;
return round(abs(time($date_2) - time($date_1)) / $one_day);
}
[#7] siegfried at anggit dot com [2012-07-24 23:03:02]
elapsed time function with precision:
<?php
function elapsed_time($timestamp, $precision = 2) {
$time = time() - $timestamp;
$a = array('decade' => 315576000, 'year' => 31557600, 'month' => 2629800, 'week' => 604800, 'day' => 86400, 'hour' => 3600, 'min' => 60, 'sec' => 1);
$i = 0;
foreach($a as $k => $v) {
$$k = floor($time/$v);
if ($$k) $i++;
$time = $i >= $precision ? 0 : $time - $$k * $v;
$s = $$k > 1 ? 's' : '';
$$k = $$k ? $$k.' '.$k.$s.' ' : '';
@$result .= $$k;
}
return $result ? $result.'ago' : '1 sec to go';
}
echo elapsed_time('1234567890').'<br />'; // 3 years 5 months ago
echo elapsed_time('1234567890', 6); // 3 years 5 months 1 week 2 days 57 mins 4 secs ago
?>
[#8] xzxxxx7 at gmail dot com [2012-06-13 08:25:10]
hebrew time Ago function by xzxxx7
<?php
function he_timeAgo( $a ){
$b = time() - $a;
$c = array( 12 * 30 * 24 * 60 * 60, 30 * 24 * 60 * 60, 7 * 24 * 60 * 60, 24 * 60 * 60, 60 * 60, 60 );
$d = array( "???", "????", "????", "???", "???", "???" );
$e = array( "????", "??????", "??????", "????", "????", "????" );
if( $b < 60 ) return "???? ????";
for( $f=0; ( $h = $b/$c[$f] ) <= 1 && $f < 5; $f++);
return ( floor($h) > 1 ) ? sprintf( "%d %s", $h, $e[$f] ) : $d[$f];
}
?>
<!doctype html>
<html lang="he_IL" dir="rtl">
<head>
<title>[PHP] he_timeAgo function</title>
<meta charset="utf-8">
<meta name="author" content="xzxxx7">
</head>
<body>
????? ????
<?php echo he_timeAgo(1111111111);?>
</body>
</html>
[#9] salladin [2012-05-08 21:59:23]
Two quick approaches to getting the time elapsed in human readable form.
<?php
function time_elapsed_A($secs){
$bit = array(
'y' => $secs / 31556926 % 12,
'w' => $secs / 604800 % 52,
'd' => $secs / 86400 % 7,
'h' => $secs / 3600 % 24,
'm' => $secs / 60 % 60,
's' => $secs % 60
);
foreach($bit as $k => $v)
if($v > 0)$ret[] = $v . $k;
return join(' ', $ret);
}
function time_elapsed_B($secs){
$bit = array(
' year' => $secs / 31556926 % 12,
' week' => $secs / 604800 % 52,
' day' => $secs / 86400 % 7,
' hour' => $secs / 3600 % 24,
' minute' => $secs / 60 % 60,
' second' => $secs % 60
);
foreach($bit as $k => $v){
if($v > 1)$ret[] = $v . $k . 's';
if($v == 1)$ret[] = $v . $k;
}
array_splice($ret, count($ret)-1, 0, 'and');
$ret[] = 'ago.';
return join(' ', $ret);
}
$nowtime = time();
$oldtime = 1335939007;
echo "time_elapsed_A: ".time_elapsed_A($nowtime-$oldtime)."\n";
echo "time_elapsed_B: ".time_elapsed_B($nowtime-$oldtime)."\n";
?>
[#10] tav [2012-01-06 04:06:16]
Calculates the difference between $start and $s, returns a formatted string Xd Yh Zm As, e.g. 15d 23h 54m 31s. Empty sections will be stripped, returning 12d 4s, not 12d 0h 0m 4s.
Argument order (begin date, end date) doesn't matter.
<?php
function time_diff_conv($start, $s) {
$t = array( //suffixes
'd' => 86400,
'h' => 3600,
'm' => 60,
);
$s = abs($s - $start);
foreach($t as $key => &$val) {
$$key = floor($s/$val);
$s -= ($$key*$val);
$string .= ($$key==0) ? '' : $$key . "$key ";
}
return $string . $s. 's';
}
?>
[#11] instantcarma2000 at yahoo dot se [2011-10-14 14:54:35]
This is a very basic and simple function to display either min -OR- hrs and min -OR- days and hrs -OR- days depending on how many seconds are given.
Example use:
<?php
$td = time_diff($timestamp1-$timestamp2); // has to be a positive result
$td .= ($td=="now")? "":" ago"; // in this example "ago"
echo $td;
function time_diff($s){
$m=0;$hr=0;$d=0;$td="now";
if($s>59) {
$m = (int)($s/60);
$s = $s-($m*60); // sec left over
$td = "$m min";
}
if($m>59){
$hr = (int)($m/60);
$m = $m-($hr*60); // min left over
$td = "$hr hr"; if($hr>1) $td .= "s";
if($m>0) $td .= ", $m min";
}
if($hr>23){
$d = (int)($hr/24);
$hr = $hr-($d*24); // hr left over
$td = "$d day"; if($d>1) $td .= "s";
if($d<3){
if($hr>0) $td .= ", $hr hr"; if($hr>1) $td .= "s";
}
}
return $td;
}
?>
[#12] dev dot ivangc at gmail dot com [2011-08-05 03:05:52]
Here a class extension to get the a datetime in the "X time ago" format easily.
<?php
class Cokidoo_DateTime extends DateTime {
protected $strings = array(
'y' => array('1 year ago', '%d years ago'),
'm' => array('1 month ago', '%d months ago'),
'd' => array('1 day ago', '%d days ago'),
'h' => array('1 hour ago', '%d hours ago'),
'i' => array('1 minute ago', '%d minutes ago'),
's' => array('now', '%d secons ago'),
);
public function __toString() {
$now = new DateTime('now');
$diff = $this->diff($now);
foreach($this->strings as $key => $value){
if( ($text = $this->getDiffText($key, $diff)) ){
return $text;
}
}
return '';
}
protected function getDiffText($intervalKey, $diff){
$pluralKey = 1;
$value = $diff->$intervalKey;
if($value > 0){
if($value < 2){
$pluralKey = 0;
}
return sprintf($this->strings[$intervalKey][$pluralKey], $value);
}
return null;
}
}
?>
How to use:
<?php
$date = new Cokidoo_Datetime('2011-01-01');
echo $date;
?>
[#13] residualenvy at gmail dot com [2011-03-11 15:34:39]
My take on a function to find the differences between a timestamp and current time.
Format: findTime($sometime['stamp'], '%d Days, %h Hours, %m Minutes');
Always use plural it will auto correct on singular results. You don't have to include all %d,%m,%h you may include only one. To get Total Hours remaining(including days) use %ho. To get Total Minutes remaining(including hours and days) use %mo. Take a look at the format I assumed to make any changes.
<?php
function findTime($timestamp, $format) {
$difference = $timestamp - time();
if($difference < 0)
return false;
else{
$min_only = intval(floor($difference / 60));
$hour_only = intval(floor($difference / 3600));
$days = intval(floor($difference / 86400));
$difference = $difference % 86400;
$hours = intval(floor($difference / 3600));
$difference = $difference % 3600;
$minutes = intval(floor($difference / 60));
if($minutes == 60){
$hours = $hours+1;
$minutes = 0;
}
if($days == 0){
$format = str_replace('Days', '?', $format);
$format = str_replace('Ds', '?', $format);
$format = str_replace('%d', '', $format);
}
if($hours == 0){
$format = str_replace('Hours', '?', $format);
$format = str_replace('Hs', '?', $format);
$format = str_replace('%h', '', $format);
}
if($minutes == 0){
$format = str_replace('Minutes', '?', $format);
$format = str_replace('Mins', '?', $format);
$format = str_replace('Ms', '?', $format);
$format = str_replace('%m', '', $format);
}
$format = str_replace('?,', '', $format);
$format = str_replace('?:', '', $format);
$format = str_replace('?', '', $format);
$timeLeft = str_replace('%d', number_format($days), $format);
$timeLeft = str_replace('%ho', number_format($hour_only), $timeLeft);
$timeLeft = str_replace('%mo', number_format($min_only), $timeLeft);
$timeLeft = str_replace('%h', number_format($hours), $timeLeft);
$timeLeft = str_replace('%m', number_format($minutes), $timeLeft);
if($days == 1){
$timeLeft = str_replace('Days', 'Day', $timeLeft);
$timeLeft = str_replace('Ds', 'D', $timeLeft);
}
if($hours == 1 || $hour_only == 1){
$timeLeft = str_replace('Hours', 'Hour', $timeLeft);
$timeLeft = str_replace('Hs', 'H', $timeLeft);
}
if($minutes == 1 || $min_only == 1){
$timeLeft = str_replace('Minutes', 'Minute', $timeLeft);
$timeLeft = str_replace('Mins', 'Min', $timeLeft);
$timeLeft = str_replace('Ms', 'M', $timeLeft);
}
return $timeLeft;
}
}
?>
[#14] php/hotblocks/nl [2011-02-25 02:40:13]
The easiest way to get the gmtime is to use gmdate():
<?php
$gmtime = (int)gmdate('U');
?>
[#15] Yi [2011-02-23 08:29:28]
A method return GMT time (gmttime):
<?php
$gmtimenow = time() - (int)substr(date('O'),0,3)*60*60;
echo $gmtimenow . "\n";
?>
it convert current time to GMT based on time zone offset.
by frank.
[#16] karls_post at hotmail dot com [2011-01-23 03:44:57]
To accurately calculate the difference between the current time and a time in the future I use the following.
<?php
function time_difference($endtime){
$days= (date("j",$endtime)-1);
$months =(date("n",$endtime)-1);
$years =(date("Y",$endtime)-1970);
$hours =date("G",$endtime);
$mins =date("i",$endtime);
$secs =date("s",$endtime);
$diff="'day': ".$days.",'month': ".$months.",'year': ".$years.",'hour': ".$hours.",'min': ".$mins.",'sec': ".$secs;
return $diff;
}
$end_time = $future_date - time();
$difference = time_difference($end_time);
echo $difference;
//sample output
'day': 2,'month': 1,'year': 0,'hour': 2,'min': 05,'sec': 41
?>
[#17] Timo K [2010-10-02 05:49:44]
The documentation should have this info. The function time() returns always timestamp that is timezone independent (=UTC).
<?php
date_default_timezone_set("UTC");
echo "UTC:".time();
echo "<br>";
date_default_timezone_set("Europe/Helsinki");
echo "Europe/Helsinki:".time();
echo "<br>";
?>
Local time as string can be get by strftime() and local timestamp (if ever needed) by mktime().
[#18] johan dot lindskog at humlab dot umu dot se [2010-08-26 06:35:50]
I needed to convert between Unix timestamps and Windows/AD timestamps, so I wrote a pair of simple functions for it.
<?php
function unix_time_to_win_time($unix_time) {
//add the seconds between 1601-01-01 and 1970-01-01 and make it 100-nanosecond precision
$win_time = ($unix_time + 11644477200) * 10000000;
return $win_time;
}
function win_time_to_unix_time($win_time) {
//round the win timestamp down to seconds and remove the seconds between 1601-01-01 and 1970-01-01
$unix_time = round($win_time / 10000000) - 11644477200;
return $unix_time;
}
?>
[#19] John Galt [2010-08-14 15:46:26]
This is another function to calculate the difference between two times and output it in a relative format. This one, however, combines various units. In other words, it will return "3 days, 2 hours, 6 minutes, and 2 seconds ago" instead of "3 days ago."
Please bear in mind that it is intended for times that are very close together. It will not be accurate for calculating dates more than a month apart. This is because one of the units it relies on is "weeks," which do not correspond directly with months. What I'm trying to get across is, the program assumes that a month is precisely 4 weeks long, i.e. 28 days. This also means that a "year" according to this function is 336 days.
<?php
function rel_time($from, $to = null)
{
$to = (($to === null) ? (time()) : ($to));
$to = ((is_int($to)) ? ($to) : (strtotime($to)));
$from = ((is_int($from)) ? ($from) : (strtotime($from)));
$units = array
(
"year" => 29030400, // seconds in a year (12 months)
"month" => 2419200, // seconds in a month (4 weeks)
"week" => 604800, // seconds in a week (7 days)
"day" => 86400, // seconds in a day (24 hours)
"hour" => 3600, // seconds in an hour (60 minutes)
"minute" => 60, // seconds in a minute (60 seconds)
"second" => 1 // 1 second
);
$diff = abs($from - $to);
$suffix = (($from > $to) ? ("from now") : ("ago"));
foreach($units as $unit => $mult)
if($diff >= $mult)
{
$and = (($mult != 1) ? ("") : ("and "));
$output .= ", ".$and.intval($diff / $mult)." ".$unit.((intval($diff / $mult) == 1) ? ("") : ("s"));
$diff -= intval($diff / $mult) * $mult;
}
$output .= " ".$suffix;
$output = substr($output, strlen(", "));
return $output;
}
?>
The function rel_time() accepts two parameters: $from and $to. For best results, provide them as UNIX timestamps (derived from PHP's time() function). They also accept formats supported by strtotime(). $to is an optional argument and defaults to the current time.
The function will calculate the difference between $from and $to. If $from occurs after $to, the function will substitue "ago" with "from now."
Example usage:
<?php
echo rel_time("September 2, 2010 4:20 PM");
// returns "2 weeks, 4 days, 23 hours, 25 minutes, and 3 seconds from now"
?>
[#20] nickr at visuality dot com [2010-02-08 13:54:52]
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;
?>
[#21] yasmary at gmail dot com [2009-03-06 12:48:47]
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
?>
[#22] anon [2009-01-26 17:16: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.
[#23] Anonymous [2008-09-01 17:30:21]
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';
}
?>
[#24] Josh Abraham [2007-09-28 07:43:06]
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;
}
?>
[#25] by225 at yahoo dot com [2007-09-06 12:32:51]
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;
}
?>
[#26] lsd25 at hotmail dot com [2007-09-01 07:53:03]
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";
?>
[#27] send at mail dot 2aj dot net [2006-06-08 11:58:16]
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.
?>
[#28] aidan at php dot net [2005-10-07 17:14:53]
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
[#29] mayank_arya at hotmail dot com [2003-05-28 18:13:20]
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 :)
?>