Question

I'm creating comments stored in a MySQL database.

I'm logging the php time function time() as the comment is posted. That way it's displaying a message such as... "comment... posted 4 seconds ago" and if I refresh the page 2 minutes later it'd display "comment... posted 2 minutes ago"

Here's how I am entering time() into the database along with the other data:

$date=time();

// Insert data into mysql
$sql="INSERT INTO testimonials (username, comment, date) 
  VALUES ('$username', '$comment', '$date')";

Now... I grab the data like this:

while ($row = mysql_fetch_row($result) )
{
  echo "<b>Random Comment</b></br>";
  echo ("<p>\n> $row[1]"); //comment
  echo ("</br>-$row[0]</p>"); //name
  echo ("</br>$row[2]"); //date

The sample output on my server is:

Random Comment

This is the most awesome comment thing ever!!!!

-Kyle

1278905319

How could I convert the time "1278905319" into a readable format such as, "posted 4 seconds ago" or something that deals with seconds, minutes, hours, days, weeks, months, years?

Is PHP the wrong way to do it? I read about MySQL timestamping but I don't understand that or how to make it work in my case.

So my main question is, how to format the time into a readable time on output. "2 seconds ago"

Thank you. =)

Was it helpful?

Solution

Here's a function I found here, written by one John McClumpha:

<?php
function RelativeTime($timestamp){
    $difference = time() - $timestamp;
    $periods = array("sec", "min", "hour", "day", "week", "month", "years", "decade");
    $lengths = array("60","60","24","7","4.35","12","10");

    if ($difference > 0) { // this was in the past
        $ending = "ago";
    } else { // this was in the future
        $difference = -$difference;
        $ending = "to go";
    }       
    for($j = 0; $difference >= $lengths[$j]; $j++) $difference /= $lengths[$j];
    $difference = round($difference);
    if($difference != 1) $periods[$j].= "s";
    $text = "$difference $periods[$j] $ending";
    return $text;
}

OTHER TIPS

First, let MySQL insert the date for you by using an auto-updating timestamp field:

CREATE TABLE `table_a` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` VARCHAR(255),
  `comment` TEXT,
  `date` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB;

This way, you don't need to worry about inserting the date from your PHP code, and if you do any testing from elsewhere - from the MySQL client, for instance, the date will still be inserted correctly.

You should also use the PHP DateTime Class (requires PHP 5.3.0 or greater), as it makes working with dates and times quite simple. Here's an example of getting some information from the database, and returning a formatted time interval:

$result = $mysqli->query(
    'SELECT ' .
    '`id`, ' .
    '`username`, ' .
    '`comment`, ' .
    '`date`, ' .
    'NOW(), ' .
    'FROM table');

$row = $result->fetch_assoc();

print_r($row);
Array
(
    [id] => 1
    [username] = 'Fred'
    [comment] = 'My first post'
    [date] => 2009-09-28 07:08:12
    [now] => 2010-07-12 08:47:03
)

$now = new DateTime($row['now']);
$post = new DateTime($row['date']);
$interval = $post->diff($now);
echo $interval->format('%m months, %d days, %d days, %h hours, %m minutes, %s seconds');

// 9 months, 14 days, 14 days, 1 hours, 9 minutes, 51 seconds

You can format the interval however you like using the DateInterval::format parameters. By getting MySQL to return NOW(), you ensure that any time discrepancy between your application server (the one running PHP), and your database server is avoided.

If you need complex time calculations, check out symfony's DateHelper, especially distance_of_time_in_words as found in the source. This is a very powerfull method does knows a very fine grained time calculation (e.g. 5 seconds ago, 20 seconds ago, about 1 minute ago, 10 minutes ago,...)


If you just want to have the date formatted, you can format it via MySQL:

SELECT your_fields, FROM_UNIXTIME(date, 'H:%i:%s') FROM table;

would give you 12:24:59 for example.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top