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
time
(PHP 4, PHP 5)
time — Gibt den aktuellen Unix-Timestamp/Zeitstempel zurück
Beschreibung
int time
( void
)
Gibt die seit Beginn der Unix-Epoche (Januar 1 1970 00:00:00 GMT) bis jetzt vergangenen Sekunden zurück.
Beispiele
Beispiel #1 time()-Beispiel
<?php
$nextWeek = time() + (7 * 24 * 60 * 60);
// 7 Tage; 24 Stunden; 60 Minuten; 60 Sekunden
echo 'Jetzt: '. date('Y-m-d') ."\n";
echo 'Naechste Woche: '. date('Y-m-d', $nextWeek) ."\n";
// oder strtotime() verwenden:
echo 'Naechste Woche: '. date('Y-m-d', strtotime('+1 week')) ."\n";
?>
Das oben gezeigte Beispiel erzeugt eine ähnliche Ausgabe wie:
Jetzt: 2005-03-30 Naechste Woche: 2005-04-06 Naechste Woche: 2005-04-06
Anmerkungen
Tipp
Der Timestamp des Beginns der aktuellen Anfrage steht seit PHP 5.1 in der Variablen $_SERVER['REQUEST_TIME'] zur Verfügung.
Siehe auch
- date() - Formatiert ein(e) angegebene(s) Ortszeit/Datum
- microtime() - Gibt den aktuellen Unix-Timestamp/Zeitstempel mit Mikrosekunden zurück
time
rspenc29 at gmail dot com
14-Jun-2007 03:33
14-Jun-2007 03:33
sunjith
07-Jun-2007 04:57
07-Jun-2007 04:57
In ron's script, the while loop condition should be ($i >0). Otherwise, the index $lengths goes to -1 which will show an error.
ron at sdcausa dot org
01-Jun-2007 10:26
01-Jun-2007 10:26
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;
}
}
shdowhawk at gmail dot com
19-May-2007 03:40
19-May-2007 03:40
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;
}
}
joncampell at gmail dot com
08-May-2007 10:07
08-May-2007 10:07
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.
jason at thinkingman dot org
26-Apr-2007 06:58
26-Apr-2007 06:58
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
)
webmaster[at]auscoder[dot]com
25-Apr-2007 04:36
25-Apr-2007 04:36
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;
}
?>
greg at mix.lycos.com
24-Apr-2007 09:46
24-Apr-2007 09:46
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;
}
?>
john at motdidr dot com
13-Mar-2007 12:01
13-Mar-2007 12:01
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
jh2000 at root24 dot eu
25-Feb-2007 09:08
25-Feb-2007 09:08
Just a small notice:
use the time() function instead of date("U"), it is much faster (about 1000 times~)
tristan at trinicle dot net
23-Nov-2006 11:10
23-Nov-2006 11:10
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;
}
?>
andrew dot macrobert at gmail dot com
29-Oct-2006 11:33
29-Oct-2006 11:33
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;
}
?>
andrew dot macrobert at gmail dot com
22-Oct-2006 08:47
22-Oct-2006 08:47
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";
}
}
}
}
}
?>
krisdover at hotmail dot com
09-Sep-2006 06:54
09-Sep-2006 06:54
# 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"><<</a></td>
<td width="14%" bgcolor="#66FF99">
<a href="?sel_date=<?= $prev_month ?>" style="text-decoration: none" title="Prevous Month"><</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">></a></td>
<td width="14%" bgcolor="#66FF99">
<a href="?sel_date=<?= $next_year ?>" style="text-decoration: none" title="Next Year">>></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>
STaRDoGGCHaMP
21-Jul-2006 08:34
21-Jul-2006 08:34
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"
?>
send at mail dot 2aj dot net
08-Jun-2006 08:58
08-Jun-2006 08: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.
?>
info at exitorange dot com
21-Feb-2006 05:11
21-Feb-2006 05:11
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));
emory dot smith at gmail dot com
20-Feb-2006 01:17
20-Feb-2006 01:17
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);
?>
aidan at php dot net
08-Oct-2005 02:14
08-Oct-2005 02:14
* 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
mayank_arya at hotmail dot com
29-May-2003 03:13
29-May-2003 03: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 :)
?>
paul at honeylocust dot com
13-Jun-2002 09:56
13-Jun-2002 09:56
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.
matt at blockdev dot net
22-Sep-2001 04:04
22-Sep-2001 04:04
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;
08-Sep-2000 09: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);