|
|
 |
time (PHP 3, PHP 4, PHP 5) time -- Return current Unix timestamp Descriptionint time ( void )
Returns the current time measured in the number of seconds since
the Unix Epoch (January 1 1970 00:00:00 GMT).
Example 1. time() example |
<?php
$nextWeek = time() + (7 * 24 * 60 * 60);
echo 'Now: '. date('Y-m-d') ."\n";
echo 'Next Week: '. date('Y-m-d', $nextWeek) ."\n";
?>
|
The above example will output
something similar to: Now: 2005-03-30
Next Week: 2005-04-07 |
|
See also date() and microtime().
User Contributed Notes
time
petar74 at hotmail dot com
25-Apr-2005 11:00
I am new to php so if you have any comments send it pls.
I needed users time ,time on his PC and what ever I found online it was some case where user was asked for time zone trought some form aaand that was ugly to me so I make this solution wich is working .. I belive .
first part was in javascript.. I needed users time zone offset (but I dont wish user to tipe or klick anything) so I add to my page somethign like this
var now = new Date();
var tzo = now.getTimezoneOffset(); // time zone ofset
var lnk='tmz.php?gmt='+ tzo ; //make it part of a link
window.location=lnk; // and relocate and pass it
and then simple calculation
<?php
if ($gmt < 0 ) {
$time=time()-($gmt*60); }
else
{
$time=time()+($gmt*60) ; }
$user_time=gmdate('g:i a', $time); print $user_time ;
?>
I hope this will help some one :)
alex
25-Apr-2005 02:39
sorry, quick correction on previous post
JavaScript's getTime() actually uses GMT, you must incorporate the getTimezoneOffset() in order to make it any different then PHP's time().
like so:
<script language="JavaScript">
function addTime() {
var d = new Date();
var TI = document.getElementById('time');
TI.value=Math.floor(d.getTime()/1000)-(d.getTimezoneOffset()*60);
}
</script>
simply set that function as the onsubmit of any form the has a hidden <input> with id="time" any you're golden. getTimezoneOffset gives the offset difference in minutes, hence the *60. I hope this is of assistance to someone.
phil at goli dot at
17-Apr-2005 08:43
new version: corrected and improved!
This function returns the correct DST time for EU countries. Change $TZOffset for your timezone. Use myDST() instead of time().
Other examples of usage:
getdate(myDST());
date('H:i:s', myDST());
getdate(myDST());
function myDST()
{
$TZOffset = 1;
// MEZ = UTC + TZOffset:
$myMEZ = mktime(gmdate("H") + $TZOffset);
$myMESZ = mktime(gmdate("H") + $TZOffset + 1);
$myMEZ_year = date("Y", $myMEZ);
$tmp = strtotime("last Sunday", mktime(0, 0, 0, 4, 1, $myMEZ_year));
$myLastSundayMarch = mktime(2, 0, 0, date("m", $tmp), date("d", $tmp), date("Y", $tmp));
$tmp = strtotime("last Sunday", mktime(0, 0, 0, 11, 1, $myMEZ_year));
$myLastSundayOctober = mktime(3, 0, 0, date("m", $tmp), date("d", $tmp), date("Y", $tmp));
if ( ($myMEZ >= $myLastSundayMarch) && ($myMESZ < $myLastSundayOctober) )
{
return $myMESZ; // summertime
}
else
{
return $myMEZ; // normal time ("wintertime")
}
}
NOSPAM dot justin at jshewell dot com
17-Apr-2005 03:04
This function (see the posting below) has been edited to allow for countries that don't use Daylight Savings Time and will return the time in any timezone (as specified in $TZOffset).
Examples of usage:
date("H:i",myDST(4,false));
//returns the time in a GCC country (no DST and 4 hours ahead of UTC)
function myDST($TZOffset,$DST) {
if(!isset($TZOffset)) {$TZOffset = 0;} //if the user doesn't set a timezone, use UTC
//$TZOffset = 4; //GCC Timezone (UTC + 4);
//echo $TZOffset;
// MEZ = UTC + TZOffset:
$myMEZ = mktime(gmdate("H") + $TZOffset);
$myMEZ_year = date("Y", $myMEZ);
$tmp = strtotime("last Sunday", mktime(0, 0, 0, 4, 1, $myMEZ_year));
$myLastSundayMarch = mktime(2, 0, 0, date("m", $tmp), date("d", $tmp), date("Y", $tmp));
$tmp = strtotime("last Sunday", mktime(0, 0, 0, 11, 1, $myMEZ_year));
$myLastSundayOctober = mktime(3, 0, 0, date("m", $tmp), date("d", $tmp), date("Y", $tmp));
if($DST) {
if(($myMEZ >= $myLastSundayMarch) && ($myMEZ < $myLastSundayOctober)) {
return mktime(gmdate("H") + $TZOffset + 1); // summertime
} else {
return mktime(gmdate("H") + $TZOffset); // normal time ("wintertime")
}
} else {return mktime(gmdate("H") + $TZOffset);} // no Daylight Savings Time (DST)
}
phil at goli dot at
16-Apr-2005 04:36
This function returns the correct DST time for EU countries. Change $TZOffset for your timezone. Use myDST() instead of time().
Other examples of usage:
getdate(myDST());
date('H:i:s', myDST());
getdate(myDST());
function myDST()
{
$TZOffset = 1;
// MEZ = UTC + TZOffset:
$myMEZ = mktime(gmdate("H") + $TZOffset);
$myMEZ_year = date("Y", $myMEZ);
$tmp = strtotime("last Sunday", mktime(0, 0, 0, 4, 1, $myMEZ_year));
$myLastSundayMarch = mktime(2, 0, 0, date("m", $tmp), date("d", $tmp), date("Y", $tmp));
$tmp = strtotime("last Sunday", mktime(0, 0, 0, 11, 1, $myMEZ_year));
$myLastSundayOctober = mktime(3, 0, 0, date("m", $tmp), date("d", $tmp), date("Y", $tmp));
if ( ($myMEZ >= $myLastSundayMarch) && ($myMEZ < $myLastSundayOctober) )
{
return mktime(gmdate("H") + $TZOffset + 1); // summertime
}
else
{
return mktime(gmdate("H") + $TZOffset); // normal time ("wintertime")
}
}
neoyahuu at yahooku dot com
08-Apr-2005 04:05
i decide to create a function for converting MySQL timestamp(14) to datetime..
function datetime($YYYYMMDDHHMMSS) {
list($year,$month,$day,$hour,$minute,$seconds) = sscanf($YYYYMMDDHHMMSS,'%4s%2s%2s%2s%2s%2s');
return date('Y-m-d h:i:s', mktime($hour,$minute,$seconds,$month,$day,$year));
}
echo datetime("20040422090941");
//output 2004-04-22 09:09:41
mlseuk at hotmail dot com
14-Mar-2005 10:47
Here's a very simple and easily extensible way of calculating elapsed times. It automatically takes care of leap years and the like and doesn't require that you do any complicated modulo arithmetic at all! It accepts a timestring in a format that is compatible with GNU time formats (i.e. anything that strtotime will accept) and returns the elapsed time as an associative array. Its output has 1 second accuracy. Probably needs a bit off fiddling to get it working perfectly.
function elapsed_time($timestring)
{
//Get the time difference.
$x = split(",", date("Y,m,d,H,i,s", time() - strtotime($timestring)));
//Return an associative array. Subtract 01.01.1970 because
//time() and strtotime() return time values WRT the Unix Epoch.
return array("years" => $x[0] - 1970,
"months" => $x[1] - 1,
"days" => $x[2] - 1,
"hours" => $x[3],
"minutes" => $x[4],
"seconds" => $x[5]);
}
webmaster at com1net dot com
05-Mar-2005 10:52
Here's an updated function which adds the months and weeks. . .
function calcElapsedTime($time)
{
// calculate elapsed time (in seconds!)
$diff = time()-$time;
$yearsDiff = floor($diff/60/60/24/365);
$diff -= $yearsDiff*60*60*24*365;
$monthsDiff = floor($diff/60/60/24/30);
$diff -= $monthsDiff*60*60*24*30;
$weeksDiff = floor($diff/60/60/24/7);
$diff -= $weeksDiff*60*60*24*7;
$daysDiff = floor($diff/60/60/24);
$diff -= $daysDiff*60*60*24;
$hrsDiff = floor($diff/60/60);
$diff -= $hrsDiff*60*60;
$minsDiff = floor($diff/60);
$diff -= $minsDiff*60;
$secsDiff = $diff;
return (''.$yearsDiff.' year'.(($yearsDiff <> 1) ? "s" : "").', '.$monthsDiff.' month'.(($monthsDiff <> 1) ? "s" : "").', '.$weeksDiff.' week'.(($weeksDiff <> 1) ? "s" : "").', '.$daysDiff.' day'.(($daysDiff <> 1) ? "s" : "").', '.$hrsDiff.' hour'.(($hrsDiff <> 1) ? "s" : "").', '.$minsDiff.' minute'.(($minsDiff <> 1) ? "s" : "").', '.$secsDiff.' second'.(($secsDiff <> 1) ? "s" : "").'');
}
Call with:
$last = calcElapsedTime(mktime(0, 0, 0, 6, 20, 2000));
echo "Online: ".$last.".<br>";
Output:
Online: 4 years, 8 months, 2 weeks, 1 day, 21 hours, 1 minute, 29 seconds.
webmaster at com1net dot com
05-Mar-2005 08:31
In response to kirua at coder-studio spammy dot com's post, I liked his time function a lot, and so I made it more user friendly. I added a years feature, and it also automatically adds or removes the 's' on the end of year(s), day(s), hour(s) minute(s) second(s) based on the number thats output. . .
<?
function calcElapsedTime($time)
{
$diff = time()-$time;
$yearsDiff = floor($diff/60/60/24/365);
$diff -= $yearsDiff*60*60*24*365;
$daysDiff = floor($diff/60/60/24);
$diff -= $daysDiff*60*60*24;
$hrsDiff = floor($diff/60/60);
$diff -= $hrsDiff*60*60;
$minsDiff = floor($diff/60);
$diff -= $minsDiff*60;
$secsDiff = $diff;
return ($yearsDiff.' year'.(($yearsDiff <> 1) ? "s" : "").', '.$daysDiff.' day'.(($daysDiff <> 1) ? "s" : "").', '.$hrsDiff.' hour'.(($hrsDiff <> 1) ? "s" : "").', '.$minsDiff.' minute'.(($minsDiff <> 1) ? "s" : "").', '.$secsDiff.' second'.(($secsDiff <> 1) ? "s" : ""));
}
?>
To use simply feed it something like:
$operation = calcElapsedTime(mktime(0, 0, 0, 6, 20, 2000)); // time elapsed since 6/20/2000.
echo "This website has been in operation $operation.<br>";
Output:
This website has been in operation 4 years, 259 days, 18 hours, 1 minute, 12 seconds.
-or-
echo "This page was last updated ".calcElapsedTime(filectime('duration.php')).".<br>"; // time elapsed since duration.php was last updated.
Output:
This page was last updated 0 years, 0 days, 1 hour, 12 minutes, 55 seconds.
tyconzor at hotmail dot com
16-Feb-2005 03:18
Just a simple way to calculate the time passed since a certain date:
<?php
$delta = time() - mktime(0, 0, 0, 2, 7, 2005);
echo round($delta/(60*60*24),2);
?>
I know this is a trivial problem, but this script can be handy for uptime statistics on your page or something similar.
cory^dot^mawhorter^at^gmail^dot^com
10-Feb-2005 08:53
i apoligize, my seconds_to_time function below returns some invalid results
<?php
if ($retArr['days'] > 0) $seconds -= $retArr['days'] * 86400;
?>
cory^dot^mawhorter^at^gmail^dot^com
04-Feb-2005 01:45
here are a couple useful functions i wrote
<?php
function time_to_seconds ($minutes, $hours=NULL, $days=NULL, $years=NULL) {
$seconds = 0;
$seconds += $minutes * 60;
if ($hours != NULL) $seconds += $hours * 3600;
if ($days != NULL) $seconds += $days * 86400;
if ($years != NULL) $seconds += $years * 31536000;
return $seconds;
}
function seconds_to_time ($seconds) {
$retArr['years'] = floor ($seconds / 31536000);
if ($retArr['years'] > 1) $seconds -= $retArr['years'] * 31536000;
$retArr['days'] = floor ($seconds / 86400);
if ($retArr['days'] > 1) $seconds -= $retArr['days'] * 86400;
$retArr['hours'] = floor ($seconds / 3600);
if ($retArr['hours'] > 1) $seconds -= $retArr['hours'] * 3600;
$retArr['minutes'] = floor ($seconds / 60);
if ($retArr['minutes'] > 1) $seconds -= $retArr['minutes'] * 60;
$retArr['seconds'] = $seconds;
return $retArr;
}
?>
lzcaprio at gmail dot com
04-Feb-2005 07:32
get the decimal seconds from a current time
<?php
$micro = explode(' ', microtime());
echo substr(number_format($micro[0],1,'',''),-1)."<br>";
echo date("s");
?>
dan at skyinternet dot co dot uk
10-Jan-2005 08:02
Another countdown script:
<?php
$then = mktime(0, 0, 0, 9, 3, 2004);
$now = time();
$until = $then - $now;
$month = date('n', $until);
$day = date('j', $until);
$hour = date('g', $until);
$minute = date('i', $until);
$second = date('s', $until);
echo '<p>There are ' . $month . ' months, ' . $day . ' days, ' . $hour . ' hours, ' . $minute . ' minutes, and ' . $second . ' seconds until event!</p>';
?>
Regards,
webmaster at protonage dot net
28-Dec-2004 10:59
Many people have asked me what's an easy way to implement time-stamp time-zone offsets. Here's a simple class I made that has a function that returns a time-stamp calculated with a time-zone offset argument.
<?php
class MyTimeZone {
const TIMEZONE_SERVER_OFFSET = -5; public function timeOffset($offset = null)
{
if (is_int($offset)) {
$local_offset = $offset - self::TIMEZONE_SERVER_OFFSET;
return time() + 3600 * $local_offset;
}
return time();
}
}
$time = new MyTimeZone();
echo date('h:i:s a', $time->timeOffset(-8)); ?>
cheers.
moritz at barafranca dot com
15-Dec-2004 11:00
Another function that transforms a number of seconds to a more readable time.
I made it specially for displaying the duration of songs from a playlist and to display the total time of the playlist, but it can be useful for a lot of other things.
The function comes with three types of output, one with no suffix at all, and the others being with a short and long suffix.
<?
function duration ($seconds, $suffix=FALSE) {
$takes_time = array(604800,86400,3600,60,0);
$suffixes = array("Week","Day","Hour","Minute","Second");
$delimeter = array(" W ", " D ", ":",":","");
$output = "";
foreach ($takes_time as $key=>$val) {
${$suffixes[$key]} = ($val == 0) ? $seconds : floor(($seconds/$val));
$seconds -= ${$suffixes[$key]} * $val;
if (${$suffixes[$key]} > 0 || (!empty($output) && $suffix == FALSE)) {
if ($val == 0 && $suffix == FALSE && empty($output)) {
$output .= "00:";
}
$output .= ($key > 1 && strlen(${$suffixes[$key]}) == 1 && $suffix == FALSE) ? "0".${$suffixes[$key]} : ${$suffixes[$key]};
if ($suffix == "short") {
$output .= substr($suffixes[$key],0,1)." ";
}
elseif ($suffix == "long") {
$output .= (${$suffixes[$key]} > 1) ? " ".$suffixes[$key]."s " : " ".$suffixes[$key]." ";
}
else {
$output .= $delimeter[$key];
}
}
}
return $output;
}
echo duration(24233); echo duration(22303,'short'); echo duration(22309,'long'); ?>
jtacon at php dot net
13-Dec-2004 10:36
Another function to convert seconds to human readable string:
function secsToText($time = 0) {
$hours = (int)floor($time/3600);
$minutes = (int)floor($time/60)%60;
$seconds = (int)$time%60;
if($hours==1) $txt = "$hours hour";
else if($hours>1) $txt = "$hours hours";
if($txt and $minutes>0 and $seconds>0) $txt .= ", ";
else if($txt and $minutes>0 and $seconds==0) $txt .= " and ";
$s = ($minutes>1) ? "s" : NULL;
if($minutes>0) $txt .= "$minutes minute$s";
$s = ($seconds>1) ? "s" : NULL;
if($txt and $seconds>0) $txt .= " and ";
if($seconds>0) $txt .= "$seconds second$s";
else if(!$txt and $seconds==0) $txt = "0 seconds";
return $txt;
}
print secsToText(86399); // Returns '23 hours, 59 minutes and 59 seconds'
print secsToText(86400); // Returns '24 hours'
print secsToText(86401); // Returns '24 hours and 1 second'
HTH.
Javier Tacón.
florent at arpact dot org
29-Nov-2004 08:40
a function that takes a seconds duration and returns a human formatted duration (days, hours, minutes). Usefull when you have to calculate a duration after a timestamp difference.
function duration($duration) {
$jours = floor(($duree/86400));
$duration = $duration % 86400;
$heures = floor(($duration/3600));
$duration = $duration % 3600;
$minutes = floor(($duree/60));
$duration = $duration % 60;
printf('%dj %02dh %02dmin',$jours,$heures,$minutes);
}
xaxisx at gmail dot com
21-Nov-2004 05:37
Here is a simple tool, that will convert a timestamp (created with mktime()) into a count down until that event (in which the name of the event can also be specified)....
<?php
function converttime($event, $thing)
{
$time = time();
$date = date("r", $event);
$eval = $event - $time;
$ydiv = $eval / 31536000;
$ymod = $eval % 31536000;
$year = floor($ydiv);
$ndiv = $ymod / 2592000;
$nmod = $ymod % 2592000;
$mont = floor($ndiv);
$wdiv = $nmod / 604800;
$wmod = $nmod % 604800;
$week = floor($wdiv);
$ddiv = $wmod / 86400;
$dmod = $wmod % 86400;
$days = floor($ddiv);
$hdiv = $dmod / 3600;
$hmod = $dmod % 3600;
$hour = floor($hdiv);
$mdiv = $hmod / 60;
$mmod = $hmod % 60;
$minu = floor($mdiv);
echo "$year years, $mont months, $week weeks, $days days, $hour hours, $minu minutes and $mmod seconds\n";
echo "until $date, $thing";
}
$open = mktime(1, 08, 0, 9, 20, 2009);
$name = "my 20th birthday";
converttime($open, $name);
?>
11-Nov-2004 08:49
Apparently the time() function doesn't always return GMT. It returns local time here, which is several hours off of GMT.
geoff at sussex dot co dot uk
27-Oct-2004 10:57
In reply to joshuaditty:
The following does the same thing and is perhaps neater ;)
<?php
$events_time = Timestamp of the date;
$time_left = $events_time - time();
$time_left = gmdate("z\d G\h i\m s\s", $time_left);
?>
edsarkiss-at-yahoo-dot-com
23-Oct-2004 01:41
jonatan -- as the docs state, the time() function already returns the "number of seconds since the UNIX epoch -- Jan 1 1970 00:00:00 GMT".
by applying the local timezone offset to time(), you are actually moving out of GMT.
Here are some things to keep in mind:
1) if you're dealing in UNIX timestamps, the figure is ALWAYS in GMT. There is no notion of timezone in UNIX timestamps. This is merely a counter of the number of seconds since the epoch. Timezone is irrelevant. There is no such thing as a UNIX timestamp that is in a different timezone.
2) if you need to convert this to a localized time, then use localtime(time()). This returns an array of values you may then manipulate or pass to other functions like ....
3) mktime() returns a UNIX timestamp, which means that this is ALWAYS in GMT. The timezone/dst values that you pass in are taken into consideration, but the value that comes out is a UNIX timestamp, hence, GMT. see (1) above.
I actually think someone should remove the post from jonatan below, as it is misleading. I know many engineers (myself included) who are confused by UNIX timestamps at first.
gnif at spacevs dot com
18-Oct-2004 04:57
joshuaditty at cardinal-points dot com
12-Sep-2004 10:33
Sometimes you'll need to display the amount of time left before a certain event occurs (like the end of an auction) in a format like this:
2d 4h 59m 23s
This can be done using three lines of code:
<?php
$events_time = Timestamp of the date;
$time_left = $events_time - time();
$time_left = (floor($time_left/86400))."d ".floor(($time_left-(floor($time_left/86400)*86400))/3600)."h ".floor(($time_left-(floor($time_left/3600)*3600))/60)."m ".floor($time_left-(floor($time_left/60))*60)."s";
?>
rehfeld.us
28-Aug-2004 04:37
in reply to : flobee at gmx dot net
Id just like to caution those who are considering adding enviornment variables to windoes. This can cause a world of trouble.
I noticed that adding the enviornment variable *TZ* with the value *GMT* (without the *asteriks of course) will make the javascript Date() object act differently.
for example,
<script type="text/javascript>
var now = new Date();
var hour = now.getHours();
document.write(hour); // outputs the GMT hour, NOT the SYSTEM hour!
</script>
normally you would expect the output to be the same hour as your system clock, but if you add the TZ env var it will output the time in GMT instead
this was using opera 7.5x, i would imagine identical behaviour in all browsers
hope this saves someone the headache i just went through
john dot j at fphoenix dot co dot uk
06-Aug-2004 02:20
An alternative to passing an offsetted time() value to date() is to set the environment var TZ to the desired time zone before doing the date() call. HTH.
webmaster at programmershaven dot org
17-Jun-2004 02:28
It seems senseless to do the manipulation shown previous to this note, to show the date in GMT. Why?
The time() function returns the timestamp in GMT. The date() function adds the offset of the server to this timestamp.
Using gmdate(), however, passes the time right through without adding any offsets at all.
Thus to get the GMT time:
echo gmdate('l, F j, Y', time());
But to get the time of, say, GMT -0100:
echo gmdate('l, F j, y', time() - 3600);
daniel at NO dot brightbyte dot SPAM dot de
14-Jun-2004 09:55
in response to the comments by gnif at spacevs dot com and by HW: time() does NOT add the timezone-offset! However, the date()-function does so before outputting the formated time. This also means that, at least in theory, time() will return the exact SAME timestamp on the server as it does on the client side, regardless of the time zone they are in. But naturally, there is no way in PHP to run time() on the client side.
More precisely: As stated in the documentation, time() returns the number of seconds since the epoch. This is defined to be in UTC (or GMT) by the POSIX standard, and at least on my boxes it is exactly that (PHP 4.3.4 on Apache 2.0.48 on RedHat, and PHP 4.3.3 on Apache 1.3.29 on Debian). The fact that date() adds the timezone-offset before formating is compliant to the way this is done by many API's, for instance by the Perl time libraries.
However, it does not seem to be at all possible to have date() display the date in a different timezone, without manually adding/subtracting the offset from the epoch-value -- wich is not the Right Thing to do, beacuse it is not reflected by the T and Z format patterns. IMHO, date() should have an optional parameter for the time zone, which could then be used by Z and T. A simple offset in seconds would be sufficient, but a symbolic zone name, or at least a symbolic offset of the form +0500, would be very handy.
As of now, to display a formated time/date in GMT, use the method suggested by gnif at spacevs dot com:
<?
print date("H:i:s",time()-date("Z")) . " GMT";
?>
this will work fine als long as you don't have T or Z in you date-format-pattern -- that would lead to confusion. Also, the naming of the gmtime() function he suggested is misleading and should be avoided.
HTH
HW
07-Jun-2004 01:33
Note that this returns the time according to the _server's_ clock, not the client's. This shouldn't have to be mentioned, but it's amazing how often people ask about it.
gnif at spacevs dot com
06-Jun-2004 09:44
The time() function returns a timestamp with the timezone added to it, here is a function to return the current gmt time.
function gmtime() {return time() - date('Z');}
------
http://www.spacevs.com
kirua at coder-studio spammy dot com
02-Jun-2004 12:46
Hi all,
in response to a message from jcarroll at nospam theworld dot com, 18-Sep-2003 05:58 :
To calculate the elapsed time since a certain time(), I'd rather do this:
function calcElapsedTime($time)
{
// calculate elapsed time (in seconds!)
$diff = time()-$time;
$daysDiff = 0; $hrsDiff = 0; $minsDiff = 0; $secsDiff = 0;
$sec_in_a_day = 60*60*24;
while($diff >= $sec_in_a_day){$daysDiff++; $diff -= $sec_in_a_day;}
$sec_in_an_hour = 60*60;
while($diff >= $sec_in_an_hour){$hrsDiff++; $diff -= $sec_in_an_hour;}
$sec_in_a_min = 60;
while($diff >= $sec_in_a_min){$minsDiff++; $diff -= $sec_in_a_min;}
$secsDiff = $diff;
return ('(elapsed time '.$daysDiff.'d '.$hrsDiff.'h '.$minsDiff.'m '.$secsDiff.'s)');
}
that way, you avoid using lots of divisions, you avoid using floor() and you don't need to update $diff cause it's used as a counter, so it's always up to date.
have a nice day,
Nicolas Boumal
flobee at gmx dot net
11-May-2004 09:18
Windows Note: some programms need a global variable to be set in your windows config eg.: TZ = GMT
if you do not have it time() will output the time of your system clock if it is set to somethig else e.g.: TZ = GMT , php tells you your GMT time !!
-> system config -> system -> tab Advanced -> global variable
egarres at veratum.com
08-Apr-2004 12:06
function timeCaringDayLightSaving($timeZoneOffset) {
//if computer timeZoneOffset == 0 (UTC)
if (date("Z",time())==0) {
$month=date("m",time());
$day=date("d", time());
if ($month>4 && $month<10)
$dayLightSaving=1;
elseif ($month<4 || $month>10)
$dayLightSaving=0;
elseif ($month==4) {
if ($day>=7)
$dayLightSaving=1;
elseif(time()>=(strtotime("last Sunday 2:00:00")+$timeZoneOffset)) //if there WAS a Sunday this month 2 am plus offset already, that means we reached the begining of daylight saving already
$dayLightSaving=1;
else
$dayLightSaving=0;
}
elseif ($month==10) {
if ($day<=24)
$dayLightSaving=1;
elseif(time()<(strtotime("last Sunday 2:00:00")+$timeZoneOffset+(60*60)) && 10==date("m",strtotime("last Sunday 2:00:00")+$timeZoneOffset+(60*60))) //if next sunday is still in this month we are still in daylight saving time
$dayLightSaving=1;
else
$dayLightSaving=0;
}
return time()+($timeZoneOffset+(60*60*$dayLightSaving));
}
else
//Use local time
return time();
}
//-18000 seconds is for EST -05GMT
echo date("r", timeCaringDayLightSaving(-18000));
echo date("r", time());
twillaert at cereus dot be
05-Feb-2004 09:04
In response to infiwebcon:
Always try to avoid using a function on where fields in your database queries. This is the reason you did not see any usage of your indices. Every row has to be fetched, the unix_timestamp() function has to be applied, and then compared to the value you are looking for. Instead, apply the functions on the constants you specify in your where clause. The following query would give you the same result, with much better performance:
SELECT * table_name where start_datetime > from_unixtime('some_value') AND end_datetime < from_unixtime('another value')
In this case you would have used your indices. Even if you don't have indices you will see a performance boost. If you have a table with 1000 lines, you'll be calling unix_timestamp() 2000 times using a malformed query. When written correctly it's only 2 times for a table of any size.
Keep storing your timestamps as datetime because they're easier to query that way.
Note: Some databases support function based indices. Still, this would be a bad place to use them.
pting1 at yahoo
29-Jan-2004 05:06
In the CalcDateDiff function below, instead of using:
if( $date2 > $date1 )
{
die( "error: date1 has to be >= date2 in calcDateDiff($date1, $date2)" );
}
$diff = $date1-$date2;
Simply use this to avoid having to handle errors:
$diff = abs($date1-$date2);
09-Jan-2004 10:01
@jcaroll:
just using floor in calcElapsedTime() may cause less precision.
I prefer something like this:
function calcDateDiff( $date1, $date2 )
{
if( $date2 > $date1 )
{
die( "error: date1 has to be >= date2 in calcDateDiff($date1, $date2)" );
}
$diff = $date1-$date2;
$seconds = 0;
$hours = 0;
$minutes = 0;
if($diff % 86400 > 0)
{
$rest = ($diff % 86400);
$days = ($diff - $rest) / 86400;
if( $rest % 3600 > 0 )
{
$rest1 = ($rest % 3600);
$hours = ($rest - $rest1) / 3600;
if( $rest1 % 60 > 0 )
{
$rest2 = ($rest1 % 60);
$minutes = ($rest1 - $rest2) / 60;
$seconds = $rest2;
}else
$minutes = $rest1 / 60;
}else
$hours = $rest / 3600;
}else
$days = $diff / 86400;
return array( "days" => $days, "hours" => $hours, "minutes" => $minutes, "seconds" => $seconds);
}
print_r( calcDateDiff( strtotime( "now" ), strtotime( "2004-01-7 22:00:00" ) ) );
infiwebcon at comcast dot net
04-Nov-2003 01:02
In reference to the note from mwwaygoo about storing timestamps...
I have found that storing a datetime and then doing selects based on the mysql function UNIX_TIMESTAMP(field_name) has problems with regard to using indices.
For instance, let's say you have a table with a 'start_datetime' and an 'end_datetime' field that holds a standard datetime value and is a true "datetime" field. You have an index that refers to the start_datetime and end_datetime fields in place.
However, when you do a select using something like:
SELECT * from table_name where UNIX_TIMESTAMP(start_datetime) > 'some_value' AND UNIX_TIMESTAMP(end_datetime) < 'another value'
I have noticed problems using those indices when using the EXPLAIN function.
Has anyone else encountered this?
In my case, I changed the fields to INT and stored the timestamp itself. (it is misleading in that the 'timestamp' field type in mysql holds a datetime value that updates itself unless you explicitly set it). Now when I use EXPLAIN to see which index it will use, it is using the one I created.
jcarroll at nospam theworld dot com
18-Sep-2003 01:58
To calculate an elapsed time, I would suggest using _floor rather than _round (as per prev user note). _round will produce incorrect results. Try instead:
function calcElapsedTime($time)
{
// calculate elapsed time (in seconds!)
$diff = time()-$time;
$daysDiff = floor($diff/60/60/24);
$diff -= $daysDiff*60*60*24;
$hrsDiff = floor($diff/60/60);
$diff -= $hrsDiff*60*60;
$minsDiff = floor($diff/60);
$diff -= $minsDiff*60;
$secsDiff = $diff;
return ('(elapsed time '.$daysDiff.'d '.$hrsDiff.'h '.$minsDiff.'m '.$secsDiff.'s)');
}
[NOTE: I converted this from a javascript function originally posted in http://developer.irt.org/script/217.htm ... note that cited function does not appear to work with versions of Javascript after 1.3.x ...]
Sample call would be:
echo calcElapsedTime(filectime('somefile.txt'));
Output would resemble:
(elapsed time 0d 1h 12m 2s)
mayank_arya at hotmail dot com
28-May-2003 08: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.
//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 :)
hamdiggy at robotskull dot com
23-Mar-2003 05:23
this is probably already a function, but i thought i'd throw it in anyways. i just wrote this to show how long ago a folder on my server had been updated.
here's the function:
function thatDate($time){
$time=time()-$time;
$weeks=$time/604800;
$days=($time%604800)/86400;
$hours=(($time%604800)%86400)/3600;
$minutes=((($time%604800)%86400)%3600)/60;
$seconds=(((($time%604800)%86400)%3600)%60);
$timestring='last updated [';
if(round($days)) $timestring.=round($days)."d ";
if(round($hours)) $timestring.=round($hours)."h ";
if(round($minutes)) $timestring.=round($minutes)."m";
if(!round($minutes)&&!round($hours)&&!round($days)) $timestring.=" ".round($seconds)."s";
$timestring.=']';
return $timestring;
}
the argument it's looking for is the date the item was last changed. so you could call it with something like this
echo thatDate(filectime('folder/folder/file'));
and it will output something like "last updated [1d 13h 24m]".
just make sure you give it a UNIX timestamp if you send it a time from a database or something. hope somebody finds this useful.
jroberts at forumone dot com
25-Jan-2003 03:11
Looks to me like most of the example scripts on this page could better be accomplished by built-in PHP functions
strtotime() (turns a string such as a MySQL datestamp into a UNIX timestamp)
date() accepts a UNIX datestamp (optional) and lets you provide a formatting string to meet almost any need
additionally, the MySQL command DATE_FORMAT() would let you convert MySQL datestamps to pretty much any format as you pull them from the DB.
mwwaygoo at hotmail dot com
26-Jun-2002 11:16
If you are storing the date and time in a MySql database, I have found storing the time stamp as an INTEGER difficult to read when checking through the raw data. You can save a time-stamp into a datetime type and it becomes readable.
BUT when you retrieve the data it comes back as 2000-06-05 12:15:01.
Make sure your select queries use the date in this format, otherwise they give bad results, and format your retrieved entries so they are usable.
e.g.
This will give the individual entries
$my_date="2002-06-26 13:30:00";
list($year,$month,$day,$hour,$min,$sec)=explode(":", eregi_replace("[' '|-]",":", $my_date));
This will format your timestamp into a format used in your queries
$sql_query = "SELECT ... WHERE valid_until>=1025092140";
change to :
$sql_query = "SELECT ... WHERE valid_until>='" . date("Y-m-d H:i:s",1025092140) . "'";
merrick at condesamarketing dot com
21-Jun-2002 12:53
*PostgreSQL timestamp note
As mentioned above PostgreSQL does not have a timestamp, you must extract the epoch from the timestamp you stored in your database which is in PostgreSQL Timestamp format.
Getting the PostgreSQL Timestamp into your database from a form can be accomplished with a hidden form object having the value attribute set to "now()"
----------------------------------------
e.g.
<input type='hidden' name='pgsql_timestamp' value='now()'>
----------------------------------------
Now if you need to get the Unix timestamp from the PostgreSQL timestamp which is stored like
"2002-06-19 16:51:09.83662-07"
you can do the following SQL query
----------------------------------------
e.g.
"SELECT EXTRACT(EPOCH FROM pgsql_timestamp) AS unix_timestamp FROM my_pgsql_table;"
now unix_timestamp = "1024815600"
----------------------------------------
If not clear, "pgsql_timestamp" would be the name of the column which holds the PostgreSQL timestamp, it would be returned as "unix_timestamp" and would be the Unix Timestamp.
*Note your table still has the timestamp in PostgreSQL format
paul at honeylocust dot com
13-Jun-2002 02: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.
martinez at czluchow[remove-this] dot eu dot org
10-Apr-2002 09:33
Hi all.
I made a small modification to this function, so the MySQL TIMESTAMP string is converted to elements of array, which are easily accessible.
Here is my example:
-----------------------------------
function convert_time($mysql_timestamp){
// YYYYMMDDHHMMSS
//this should be in one line, i think...
if (ereg("^([0-9]{4})([0-9]{2})([0-9]{2})([0-9]{2})
([0-9]{2})([0-9]{2})",$mysql_timestamp,$res)):
$year=$res[1];
$month=$res[2];
$day=$res[3];
$hour=$res[4];
$min=$res[5];
$sec=$res[6];
return(array($year,$month,$day,$hour,$min,$sec));
else:
return(false);
endif;
}
-----------------------------------
Enjoy :-)
Martinez
/I was made in Poland/
matt at blockdev dot net
22-Sep-2001 09: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 02: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);
| |