class Util – a handy thing to have around

I have a Util class that is in my library of tools. I find myself using these functions often, thought I would share….

I like keeping my functions in a class, that way I don’t worry about redefining functions.

class Util
{

/**
* converts a unix timestamp from one timezone to another.
* You enter $tz1 or $tz2 as false, and it will assume Server Timezone.
*
* @param int $now (the timestamp in $tz1)
* @param string $tz1
* @param string $tz2
* @return int (unix timestamp in the new timezone)
*/
static function convertTimestamp($now, $tz1, $tz2)
# Input can be either a timestamp int or a strtotime()-parseable string
{
$now = trim($now);
if ( is_int($now) )
{ /* do nothing */ }
else if ( is_numeric($now) )
$now = intval($now);
else
$now = strtotime( $now );

$aServerTZ = getenv(“TZ”);

if ( !$tz1 )
$tz1 = $aServerTZ;
if ( !$tz2 )
$tz2 = $aServerTZ;

$str = date(“Y-m-d H:i:s”,$now);

putenv(“TZ=$tz1″); // Set time zone to the source
$orig_date = strtotime($str);

putenv(“TZ=$tz2″); // Set time zone to the destination
$str = date(“Y-m-d H:i:s”, $orig_date);

putenv(“TZ=$aServerTZ”); // Set time zone back to server setting.
return strtotime($str);
}

/**
* Returns a float value of the number of seconds since the epoch
*
* @return float
*/
static function getmicrotime(){
list($usec, $sec) = explode(” “,microtime());
return ((float)$usec + (float)$sec);
}

/**
* Given an integer, $bytes, returns a human readable string.
*
* @param int $bytes
* @return string
*/
static function getPrintableSize($bytes) {
if ($bytes < 1024) $size = “1 k”;
else if ($bytes < (1024*800)) $size = number_format($bytes/1024, 0) .” k”;
else if ($bytes < (1024*1024*10)) $size = number_format($bytes/1024/1024, 1) .” m”;
else $size = number_format($bytes/1024/1024, 0) .” m”;
return $size;
}

/**
* Recursively deletes a directory
*
* @param string $dirName
* @return bool
*/
static function delDir($dirName) {
if(empty($dirName) || !is_dir($dirName) ) {
return false;
}
$dir = dir($dirName);
while($file = $dir->read()) {
if($file != ‘.’ && $file != ‘..’) {
if(is_dir($dirName.’/’.$file)) {
self::delDir($dirName.’/’.$file);
} else {
if ( ! @unlink($dirName.’/’.$file) )
return false;
}
}
}
$dir->close();
if ( ! @rmdir($dirName) )
return false;
return true;
}

/**
* Creates a string suitable for use in Javascript
*
* @param string $str
* @return string
*/
static function jsAddSlashes($str) {
$pattern = array(
“/\\\\/” , “/\n/” , “/\r/” , “/\”/” ,
“/\’/” , “/&/” , “/</” , “/>/”
);
$replace = array(
“\\\\\\\\”, “\\n” , “\\r” , “\\\”” ,
“\\'” , “\\x26″ , “\\x3C” , “\\x3E”
);
return preg_replace($pattern, $replace, $str);
}

}

And to make use of one, something like this:

$start = Util::getmicrotime();
// do something
for($i=0; $i<100000; $i++) $j++;
$end = Util::getmicrotime();
$total = $end – $start;
print “Took $total seconds to complete”;

Comments are closed.