I have a function to convert timestamp to real hour, minute and second, I would to keep the format like: hh:mm:ss even if it is only some minutes and seconds, I should get 00:10:32 instead of 10:32:
// format can be either : or blank
function toTime($timestamp, $format)
{
$hours = floor($timestamp / 3600);
$minutes = floor($timestamp % 3600 / 60);
$seconds = $timestamp % 60;
if($format == ':') {
$hourDuration = sprintf('%02d:', $hours);
//echo 'hour: '.$hourDuration.'<br />';
$minDuration = sprintf('%02d:', $minutes);
//echo 'min: '.$minDuration.'<br />';
$secDuration = sprintf('%02d', $seconds);
//echo 'sec: '.$secDuration.'<br />';
$HourMinSec = $hourDuration.$minDuration.$secDuration;
} else {
$hourDuration = sprintf('%02d h', $hours);
//echo 'hour: '.$hourDuration.'<br />';
$minDuration = sprintf('%02d m', $minutes);
//echo 'min: '.$minDuration.'<br />';
$secDuration = sprintf('%02d s', $seconds);
//echo 'sec: '.$secDuration.'<br />';
$HourMinSec = '';
}
if($hourDuration > 0){
$hourDuration = $hourDuration;
} else {
$hourDuration = '';
}
if($minDuration > 0){
$minDuration = $minDuration;
} else {
$minDuration = '';
}
if($secDuration > 0){
$secDuration = $secDuration;
} else {
$secDuration = '';
}
//$HourMinSec = $hourDuration.' '.$minDuration.' '.$secDuration;
$HourMinSec = $hourDuration.$minDuration.$secDuration;
return $HourMinSec;
}
This function is used to get a video timestamp like: 1508.7397460938, and I would like to sort out, how many hours, minutes and seconds are in that video
Thanks for your assistance
I would have done it that way
function toTime($timestamp, $format)
{
$hours = floor($timestamp / 3600);
$minutes = floor($timestamp % 3600 / 60);
$seconds = $timestamp % 60;
if($format == ':') {
$hourDuration = sprintf('%02d:', $hours);
//echo 'hour: '.$hourDuration.'<br />';
$minDuration = sprintf('%02d:', $minutes);
//echo 'min: '.$minDuration.'<br />';
$secDuration = sprintf('%02d', $seconds);
//echo 'sec: '.$secDuration.'<br />';
$HourMinSec = $hourDuration.$minDuration.$secDuration;
} else {
$hourDuration = sprintf('%02d h', $hours);
//echo 'hour: '.$hourDuration.'<br />';
$minDuration = sprintf('%02d m', $minutes);
//echo 'min: '.$minDuration.'<br />';
$secDuration = sprintf('%02d s', $seconds);
//echo 'sec: '.$secDuration.'<br />';
$HourMinSec = '';
}
if($hourDuration > 0){
$hourDuration = $hourDuration;
} else {
$hourDuration = ($format == ':' ? '00:' : '00 h');
}
if($minDuration > 0){
$minDuration = $minDuration;
} else {
$minDuration = ($format == ':' ? '00:' : '00 m');
}
if($secDuration > 0){
$secDuration = $secDuration;
} else {
$secDuration = '00';
}
//$HourMinSec = $hourDuration.' '.$minDuration.' '.$secDuration;
$HourMinSec = $hourDuration.$minDuration.$secDuration;
return $HourMinSec;
}
In that case it would bring you the following result for adding
echo toTime(1508.7397460938);
Output --> 00 h25 m08 s
echo toTime(1508.7397460938,':');
Output --> 00:25:08
The other variant is to use the php ready function gmdate by typing:
echo gmdate("H:i:s", 1508.7397460938);
// Use that only if the amount of hours is less than 24 , that function would now show more than 24 hours and if so it would show inaccurate data.
Related
I have a challenge I am trying to add all the time the user has spent online but I am getting wrong totals. I am taking values from mysql database and I want to get total hours, minutes and seconds for each user. Currently I am getting totals for each session but now I want total for all sessions and display all users in a table where I have username and time spent online and must be able to filter results by date getting total time spent in hours, minutes and seconds for the filtered date. How can I do that. My code is as follows:
$i=0;
foreach ($report as $online)
{
$id = $online['userid'];
$sql = "SELECT start_time, end_time FROM user_sessions where userid=$id AND end_time !='0000-00-00' || end_time != '' LIMIT $start, $per_page";
$timeOnline = $obj->MySQLSelect($sql);
++$i;
$start = $timeOnline[$i]['start_time'];
$end = $timeOnline[$i]['end_time'];
$totalhours = get_saved_time($end, $dstart);
$sum = $totalhours;
?>
<tr class="gradeA">
<?php if (!empty($sum)): ?>
<td><? echo $generalobjAdmin->clearName($online['fname'].' '.$online['lname']); ?></td>
<td align="center"><?= Convert($sum); ?></td>
<?php endif; ?>
</tr>
<? } ?>
public function get_saved_time($end_time,$start_time)
{
$past = $start_time;
$current = strtotime($end_time);
$past = strtotime($past);
return round(abs($current-$past));
}
function Convert($seconds) {
$hours = floor($seconds / 3600);
$mins = floor(($seconds / 60) % 60);
$secs = $seconds % 60;
if (strlen($hours) == 1)
$hours = "0" . $hours;
if (strlen($secs) == 1)
$seconds = "0" . $secs;
if (strlen($mins) == 1)
$minutes = "0" . $mins;
if ($hours == 0){
$mint="";
$secondss="";
if($mins > 01){
$mint = "$mins mins";
}else{
$mint = "$mins min";
}
if($secs > 01){
$secondss = "$secs seconds";
}else{
$secondss = "$secs second";
}
$ret = "$mint $secondss";
} else {
$mint="";
$secondss="";
if($mins > 01){
$mint = "$mins mins";
}else{
$mint = "$mins min";
}
if($secs > 01){
$secondss = "$secs seconds";
}else{
$secondss = "$secs second";
}
if($hours > 01){
$ret = "$hours hrs $mint $secondss";
}else{
$ret = "$hours hr $mint $secondss";
}
}
return $ret;
}
Is there a way to see inside this function if $hours and $minutes are any other than 00:00, so that if they arent, i wont show the time?
public static function datetimedutch($date)
{
if ($date != '')
{
list($newdate, $time) = explode(' ', $date);
list($date_year, $date_month, $date_day) = explode('-', $newdate);
list($hours, $minutes, $seconds) = explode(':', $time);
$dag = array('zondag','maandag','dinsdag','woensdag','donderdag','vrijdag','zaterdag');
$maand = array('maand','januari','februari','maart','april','mei','juni','juli','augustus','september','oktober','november','december');
$weekdag = date("w", mktime($hours, $minutes, $seconds, $date_month,$date_day,$date_year));
$maandnr = date("n", mktime($hours, $minutes, $seconds, $date_month,$date_day,$date_year));
$maand_dag = date("j", mktime($hours, $minutes, $seconds, $date_month,$date_day,$date_year));
return $dag[$weekdag] . ' ' . $maand_dag . ' ' . $maand[$maandnr] . ' ' . $hours . ':' . $minutes;
}
}
This should do it :)
function datetimedutch($date)
{
if (!empty($date))
{
$someDate = strtotime($date);
$hours = date('H',$someDate);
$minutes = date('i',$someDate);
$dag = array('zondag','maandag','dinsdag','woensdag','donderdag','vrijdag','zaterdag');
$maand = array('maand','januari','februari','maart','april','mei','juni','juli','augustus','september','oktober','november','december');
$weekdag = date("w", $someDate);
$maandnr = date("n", $someDate);
$maand_dag = date("j", $someDate);
if($hours>0 || $minutes>0) {
return $dag[$weekdag] . ' ' . $maand_dag . ' ' . $maand[$maandnr] . ' ' . $hours . ':' . $minutes;
} else {
return $dag[$weekdag] . ' ' . $maand_dag . ' ' . $maand[$maandnr];
}
} else {
return false;
}
}
echo datetimedutch('2014-05-15 12:39:06');
echo "<br />";
echo datetimedutch('2014-05-15 00:00:06');
I really recommend using automated way of getting locale formatted date, for example:
function formatDateInDutch($date = null) {
$date = strtotime($date);
$currentLocale = setlocale(LC_TIME, 0);
switch (PHP_OS){
case 'WIN':
case 'WINNT':
setlocale(LC_TIME, 'Dutch');
break;
case 'LINUX':
default:
setlocale(LC_TIME, 'nl_NL');
}
// format: http://pl1.php.net/manual/en/function.strftime.php
$ret = strftime('%A %w %B %m', $date);
// has minutes, display hour:minute
if ((int)date('i', $date) != 0) {
$ret .= ' '.date('H:i', $date);
// has only hours
} elseif ((int)date('H', $date) != 0 AND (int)date('i', $date) == 0) {
$ret .= ' '.date('H', $date);
}
// restore default locale
setlocale(LC_TIME, $currentLocale);
return $ret;
}
function formatDateInDutchBetter($date = null){
$date = new DateTime($date, new DateTimeZone('Europe/Amsterdam'));
// format: http://www.icu-project.org/apiref/icu4c/classSimpleDateFormat.html#details
$formatPattern = 'EEEE e LLLL dd ';
// NOTE: $date->format and IntlDateFormatter format patterns ARE DIFFERENT!!!
// if datetime has minutes then display hour:minutes
if ((int)$date->format('i') != 0) {
$formatPattern .= 'HH:mm';
// if datetime has only minutes display minutes
} elseif ((int)$date->format('H') != 0 AND (int)$date->format('i') == 0) {
$formatPattern .= 'HH';
}
$formattedDate = IntlDateFormatter::formatObject($date, $formatPattern, 'nl_NL');
return $formattedDate;
}
print formatDateInDutch(date('Y-m-d H:m:s'));
print '<hr>';
print formatDateInDutchBetter(date('Y-m-d H:m:s'));
And I really recommend second approach: using internationalization extension from PHP. It requires enabling extension but it is platform independent and it is very easy to add/change other locales.
I have to complete 540 mins i.e 9 hours 00 minutes for today and my today in time is 11:10 AM, So I can go after 6.10pm ie my out time
function convert($time, $format = '%d:%d') {
settype($time, 'integer');
if ($time < 1) {
return;
}
$hours = floor($time / 60);
$minutes = ($time % 60);
return sprintf($format, $hours, $minutes);
}
$remain_min = 540;
$remain_time = convert($remain_min, '%02d hours %02d minutes');
echo 'You have to complete '.$remain_time.' for this week. ';
$in_timeh =11;
$in_timem = 10;
$timeformat = 'AM';
echo "Your in time" . $in_timeh. ":" . $in_timem . $timeformat . "<br />";
How to calculate it ?
I have tried this, but not seems to good, plz anyone help with better suggetion
if($timeformat == "pm"){
$in_timeh += 12;
}
$in_time_minutes = ($in_timeh * 60) + $in_timem;
$total_minutes_today = $remain_min + $in_time_minutes;
$total_minutes_today1 = floor($total_minutes_today/60).":".($total_minutes_today%60);
$newDateTime = date('h:i A', strtotime($total_minutes_today1));
echo "You can go after" . $newDateTime;
Firstly make your both in-time and out-time to time to string, and then passon that values to the following function, it will return to you the difference time.
function timeBetween($start_date,$end_date)
{
$diff = $end_date-$start_date;
$seconds = 0;
$hours = 0;
$minutes = 0;
if($diff % 86400 <= 0){$days = $diff / 86400;} // 86,400 seconds in a day
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;}
}
if($days > 0){$days = $days.' days, ';}
else{$days = false;}
if($hours > 0){$hours = $hours.' hours, ';}
else{$hours = false;}
if($minutes > 0){$minutes = $minutes.' minutes, ';}
else{$minutes = false;}
$seconds = $seconds.' seconds';
return $days.''.$hours.''.$minutes.''.$seconds;
}
try this
$date=date_create("09:00");
date_add($date,date_interval_create_from_date_string("540 minutes"));
echo date_format($date,"H:i");
You can use
$add = date("H:i:s", strtotime('+9 hours'));
echo "You can go after".$add;
I hope this helps you.
<?php
$mystartTime = "11:10:02 AM"; //hour: minute:seconds
$hrs = 60 * 60 * 9;
$mystartTimeSecs = strtotime($mystartTime);
$outTime = date('h:i:s A', $mystartTimeSecs + $hrs);
echo "You can go at " . $outTime;
echo "<br />";
$left = $mystartTimeSecs + $hrs;
$remainingTime = $left - time();
$hours = floor($remainingTime / 3600);
$minutes = floor(($remainingTime / 60) % 60);
$seconds = $remainingTime % 60;
echo "<br />";
echo "Time Left: $hours $minutes $seconds";
echo "<br />";
echo "Time Left: " . date("h:i:s", $remainingTime);
?>
I use Codeigniter and it has the timespan() function that returns the time as 1 Year, 10 Months, 2 Weeks, 5 Days, 10 Hours, 16 Minutes.
What I'd like to do is only show the time formatted in x hours ago if the time is within the last 24 hours, otherwise just show a normal datetime.
I feel like there's got to be a function already made to do this but I haven't had any luck finding it.
This is the timespan function included with Codeigniter, how can I alter it?
/**
* Timespan
*
* Returns a span of seconds in this format:
* 10 days 14 hours 36 minutes 47 seconds
*
* #access public
* #param integer a number of seconds
* #param integer Unix timestamp
* #return integer
*/
if ( ! function_exists('timespan'))
{
function timespan($seconds = 1, $time = '')
{
$CI =& get_instance();
$CI->lang->load('date');
if ( ! is_numeric($seconds))
{
$seconds = 1;
}
if ( ! is_numeric($time))
{
$time = time();
}
if ($time <= $seconds)
{
$seconds = 1;
}
else
{
$seconds = $time - $seconds;
}
$str = '';
$years = floor($seconds / 31536000);
if ($years > 0)
{
$str .= $years.' '.$CI->lang->line((($years > 1) ? 'date_years' : 'date_year')).', ';
}
$seconds -= $years * 31536000;
$months = floor($seconds / 2628000);
if ($years > 0 OR $months > 0)
{
if ($months > 0)
{
$str .= $months.' '.$CI->lang->line((($months > 1) ? 'date_months' : 'date_month')).', ';
}
$seconds -= $months * 2628000;
}
$weeks = floor($seconds / 604800);
if ($years > 0 OR $months > 0 OR $weeks > 0)
{
if ($weeks > 0)
{
$str .= $weeks.' '.$CI->lang->line((($weeks > 1) ? 'date_weeks' : 'date_week')).', ';
}
$seconds -= $weeks * 604800;
}
$days = floor($seconds / 86400);
if ($months > 0 OR $weeks > 0 OR $days > 0)
{
if ($days > 0)
{
$str .= $days.' '.$CI->lang->line((($days > 1) ? 'date_days' : 'date_day')).', ';
}
$seconds -= $days * 86400;
}
$hours = floor($seconds / 3600);
if ($days > 0 OR $hours > 0)
{
if ($hours > 0)
{
$str .= $hours.' '.$CI->lang->line((($hours > 1) ? 'date_hours' : 'date_hour')).', ';
}
$seconds -= $hours * 3600;
}
$minutes = floor($seconds / 60);
if ($days > 0 OR $hours > 0 OR $minutes > 0)
{
if ($minutes > 0)
{
$str .= $minutes.' '.$CI->lang->line((($minutes > 1) ? 'date_minutes' : 'date_minute')).', ';
}
$seconds -= $minutes * 60;
}
if ($str == '')
{
$str .= $seconds.' '.$CI->lang->line((($seconds > 1) ? 'date_seconds' : 'date_second')).', ';
}
return substr(trim($str), 0, -1);
}
}
This function will accept a string, a numeric (unix) timestamp, or a DateTime object. It also accepts jQuery.now(). Time may be in the future or past.
function time_ago($time=false, $just_now=false) {
if ($time instanceOf DateTime)
$time = $time->getTimestamp();
elseif (is_numeric($time))
$time = date('m/d/y h:i A', $time);
if (strtotime($time) === false)
$time = date('m/d/y h:i A', time());
$interval = date_create($time)->diff(date_create('now'));
$adjective = strtotime($time) > time() ? 'from now' : 'ago';
return (
$interval->days > 0 ?
$time : (
$interval->h < 1 && $interval->i < 1 && $just_now ?
'just now' :
(
$interval->h > 1 ?
$interval->h.' hour'.(
$interval->h > 1 ?
's' :
''
).' ago' :
$interval->i.' minutes'.' '.$adjective
)
)
);
}
echo time_ago('8/22/2012 5:00 PM'); // 3 hours ago
echo time_ago('8/21/2012 5:00 PM'); // 8/21/2012 5:00 PM
echo time_ago(time()); // 0 hours ago
echo time_ago(time(), true); // just now
echo time_ago(strtotime('5 days ago')); // 08/17/12 08:18 PM
echo time_ago(strtotime('5 hours ago')); // 5 hours ago
echo time_ago(strtotime('5 minutes ago')); // 5 minutes ago
echo time_ago(strtotime('+5 minutes')); // 5 minutes from now
echo time_ago('jQuery.now()', true); // just now
echo time_ago('sweet explosions, bro!', true); // just now
Documentation
date - http://php.net/manual/en/function.date.php
DateTime object - http://www.php.net/manual/en/book.datetime.php
DateInterval object - http://www.php.net/manual/en/class.dateinterval.php
is_numeric - http://php.net/manual/en/function.is-numeric.php
if( time() - $yourTime <= 86400 ) { // 86400 seconds in a day
echo timespan($yourTime);
} else {
echo date('m/d/Y \a\t H:i:s', $yourTime);
}
Don't rely on a framework, especially a bad one, for everything!
Fiddle with $format to suit your needs. Will accept almost anything as input.
<?php
/**
* RelativeTime - pretty printed
* #author Dejan Marjanovic
*/
class Site5_RelativeTime
{
private $interval = '';
public function __construct()
{
call_user_func_array(array($this, 'calculate'), func_get_args());
}
public function calculate($start, $end = NULL)
{
if ( empty($start))
return false;
if (empty($end))
$end = time();
if ( ! is_numeric($start))
$start = strtotime($start);
if ( ! is_numeric($end))
$end = strtotime($end);
if($start > $end)
$future = TRUE;
$start = '#' . $start;
$end = '#' . $end;
if ( ! ($start instanceof DateTime))
$start = new DateTime($start);
if ($end === null)
$end = new DateTime();
if ( ! ($end instanceof DateTime))
$end = new DateTime($end);
$interval = $end->diff($start);
$get_plural = function($int, $str)
{
return $int > 1? $str.'s': $str;
};
$format = array();
if ($interval->y !== 0)
$format[] = "%y " . $get_plural($interval->y, "year");
if ($interval->m !== 0)
$format[] = "%m " . $get_plural($interval->m, "month");
if ($interval->d !== 0)
$format[] = "%d " . $get_plural($interval->d, "day");
if ($interval->h !== 0)
$format[] = "%h " . $get_plural($interval->h, "hour");
if ($interval->i !== 0)
$format[] = "%i " . $get_plural($interval->i, "minute");
if ($interval->s !== 0)
{
if ( ! count($format))
{
$this->interval = "less than a minute";
return;
}
else
{
$format[] = "%s " . $get_plural($interval->s, "second");
}
}
if (count($format) > 1)
{
$format = array_shift($format) . " and " . array_shift($format);
}
else
{
$format = array_pop($format);
}
$tense = ($future === TRUE)? 'from now': 'ago';
$this->interval = $interval->format($format) . ' ' . $tense;
}
public function __toString()
{
return $this->interval;
}
}
Can I ask how can I show my tweets in my website? Like the Twitter feeds thingie. I want to have a table where in it will just show my Twitter account's tweets. Thanks guys!
$xml = simplexml_load_file('http://twitter.com/statuses/user_timeline/{yourfeed}.rss');
// display each tweet
foreach ($xml->channel->item as $tweet)
{
echo $tweet->title . '<br />';
}
Tons of other solution which can be found just by simple google search.
Check this
http://jquery.malsup.com/twitter/
http://dev.twitter.com/pages/libraries#php
Twitter provides a javascript widget that you can copy and insert into your website. Is this what you're looking for http://twitter.com/about/resources/widgets/widget_profile ?
Post this php above the head of your html:
<?php
//Replace XXXXX with your twitter username
$twitterUsername = "XXXXX";
//Change number to amount of tweets you would like to display
$amountToShow = 5;
$twitterRssFeedUrl = 'https://api.twitter.com/1/statuses/user_timeline.rss?screen_name='.$twitterUsername.'&count='.$amountToShow;
$twitterPosts = false;
$xml = #simplexml_load_file($twitterRssFeedUrl);
if(is_object($xml)){
foreach($xml->channel->item as $twit){
if(is_array($twitterPosts) && count($twitterPosts)==$amountToShow){
break;
}
$d['title'] = stripslashes(htmlentities($twit->title,ENT_QUOTES,'UTF-8'));
$description = stripslashes(htmlentities($twit->description,ENT_QUOTES,'UTF-8'));
if(strtolower(substr($description,0,strlen($twitterUsername))) == strtolower($twitterUsername)){
$description = substr($description,strlen($twitterUsername)+1);
}
$d['description'] = $description;
$d['pubdate'] = strtotime($twit->pubDate);
$d['guid'] = stripslashes(htmlentities($twit->guid,ENT_QUOTES,'UTF-8'));
$d['link'] = stripslashes(htmlentities($twit->link,ENT_QUOTES,'UTF-8'));
$twitterPosts[]=$d;
}
}else{
die('Can`t fetch the feed you requested');
}
?>
Post this in the body of your html:
<ul>
<?php
if(is_array($twitterPosts)){
echo '';
foreach($twitterPosts as $post){
$data = $post['description'];
echo '<li>'.$data.'. ';
echo 'Posted '.date('F j, Y, g:i a',$post['pubdate']).'</li>';
}
echo '';
}else{
echo 'No Twitter posts have been made';//Error message
}
?>
</ul>
With a couple more functions you can add the relative time (ie "Yesterday" "2 weeks ago" etc) and convert urls and usernames into links.
Insert the code below into the top of your php file:
<?php
######################################
## DISPLAY TWITTER FEED
######################################
//Replace XXXXX with your twitter username
$twitterUsername = "XXXXX";
//Change number to amount of tweets you would like to display
$amountToShow = 5;
$twitterRssFeedUrl = 'https://api.twitter.com/1/statuses/user_timeline.rss?screen_name='.$twitterUsername.'&count='.$amountToShow;
$twitterPosts = false;
$xml = #simplexml_load_file($twitterRssFeedUrl);
if(is_object($xml)){
foreach($xml->channel->item as $twit){
if(is_array($twitterPosts) && count($twitterPosts)==$amountToShow){
break;
}
$d['title'] = stripslashes(htmlentities($twit->title,ENT_QUOTES,'UTF-8'));
$description = stripslashes(htmlentities($twit->description,ENT_QUOTES,'UTF-8'));
if(strtolower(substr($description,0,strlen($twitterUsername))) == strtolower($twitterUsername)){
$description = substr($description,strlen($twitterUsername)+1);
}
$d['description'] = $description;
$d['pubdate'] = strtotime($twit->pubDate);
$d['guid'] = stripslashes(htmlentities($twit->guid,ENT_QUOTES,'UTF-8'));
$d['link'] = stripslashes(htmlentities($twit->link,ENT_QUOTES,'UTF-8'));
$twitterPosts[]=$d;
}
}else{
die('Can`t fetch the feed you requested');
}
######################################
## REPLACE URLS AND USERS WITH LINKS
######################################
function hyperlinks($text) {
// Props to Allen Shaw & webmancers.com
// match protocol://address/path/file.extension?some=variable&another=asf%
//$text = preg_replace("/\b([a-zA-Z]+:\/\/[a-z][a-z0-9\_\.\-]*[a-z]{2,6}[a-zA-Z0-9\/\*\-\?\&\%]*)\b/i","$1", $text);
$text = preg_replace('/\b([a-zA-Z]+:\/\/[\w_.\-]+\.[a-zA-Z]{2,6}[\/\w\-~.?=&%#+$*!]*)\b/i',"$1", $text);
// match www.something.domain/path/file.extension?some=variable&another=asf%
//$text = preg_replace("/\b(www\.[a-z][a-z0-9\_\.\-]*[a-z]{2,6}[a-zA-Z0-9\/\*\-\?\&\%]*)\b/i","$1", $text);
$text = preg_replace('/\b(?<!:\/\/)(www\.[\w_.\-]+\.[a-zA-Z]{2,6}[\/\w\-~.?=&%#+$*!]*)\b/i',"$1", $text);
// match name#address
$text = preg_replace("/\b([a-zA-Z][a-zA-Z0-9\_\.\-]*[a-zA-Z]*\#[a-zA-Z][a-zA-Z0-9\_\.\-]*[a-zA-Z]{2,6})\b/i","$1", $text);
//mach #trendingtopics. Props to Michael Voigt
$text = preg_replace('/([\.|\,|\:|\¡|\¿|\>|\{|\(]?)#{1}(\w*)([\.|\,|\:|\!|\?|\>|\}|\)]?)\s/i', "$1#$2$3 ", $text);
return $text;
}
function twitter_users($text) {
$text = preg_replace('/([\.|\,|\:|\¡|\¿|\>|\{|\(]?)#{1}(\w*)([\.|\,|\:|\!|\?|\>|\}|\)]?)\s/i', "$1#$2$3 ", $text);
return $text;
}
######################################
## DISPLAY RELATIVE DATES
######################################
//props to Osman Üngür for this (http://goo.gl/FrEMp)
function time2str($ts)
{
if(!ctype_digit($ts))
$ts = strtotime($ts);
$diff = time() - $ts;
if($diff == 0)
return 'now';
elseif($diff > 0)
{
$day_diff = floor($diff / 86400);
if($day_diff == 0)
{
if($diff < 60) return 'just now';
if($diff < 120) return '1 minute ago';
if($diff < 3600) return floor($diff / 60) . ' minutes ago';
if($diff < 7200) return '1 hour ago';
if($diff < 86400) return floor($diff / 3600) . ' hours ago';
}
if($day_diff == 1) return 'Yesterday';
if($day_diff < 7) return $day_diff . ' days ago';
if($day_diff == 7) return '1 week ago';
if($day_diff < 31) return ceil($day_diff / 7) . ' weeks ago';
if($day_diff < 60) return 'last month';
return date('F Y', $ts);
}
else
{
$diff = abs($diff);
$day_diff = floor($diff / 86400);
if($day_diff == 0)
{
if($diff < 120) return 'in a minute';
if($diff < 3600) return 'in ' . floor($diff / 60) . ' minutes';
if($diff < 7200) return 'in an hour';
if($diff < 86400) return 'in ' . floor($diff / 3600) . ' hours';
}
if($day_diff == 1) return 'Tomorrow';
if($day_diff < 4) return date('l', $ts);
if($day_diff < 7 + (7 - date('w'))) return 'next week';
if(ceil($day_diff / 7) < 4) return 'in ' . ceil($day_diff / 7) . ' weeks';
if(date('n', $ts) == date('n') + 1) return 'next month';
return date('F Y', $ts);
}
}
?>
Then post the following code in the body of your html:
<ul>
<?php
if(is_array($twitterPosts)){
echo '';
foreach($twitterPosts as $post){
$data = hyperlinks($post['description']);
$data = twitter_users($data);
echo '<li>'.$data.'. ';
echo 'Posted '.time2str(date($post['pubdate'])).'</li>';
}
echo '';
}else{
echo 'No Twitter posts have been made';//Error message
}
?>
</ul>