使用php编写php Time()到mysql

I want to log the time that a user posted a message and display it in a Twitter like fashion.

I found a function that does this but it does not work with mysqls Timestamp type.

In the instructions it says that it uses the time()format to calculate it. How should I be writing the times to my Database in order for it to work???

This is the code:

function newTime($tm,$rcs = 0) {
    // http://snipplr.com/view/17338/
    $cur_tm = time(); $dif = $cur_tm-$tm;
    $pds = array('second','minute','hour','day','week','month','year','decade');
    $lngh = array(1,60,3600,86400,604800,2630880,31570560,315705600);
    for($v = sizeof($lngh)-1; ($v >= 0)&&(($no = $dif/$lngh[$v])<=1); $v--); if($v < 0) $v = 0; $_tm = $cur_tm-($dif%$lngh[$v]);
    $no = floor($no); if($no <> 1) $pds[$v] .='s'; $x=sprintf("%d %s ",$no,$pds[$v]);
    if(($rcs == 1)&&($v >= 1)&&(($cur_tm-$_tm) > 0)) $x .= time_ago($_tm);
    return $x."ago";
}

I refuse to try and make sense out of that bloody mess :) Still laughing out loud.

However, if you want to import timestamps into a mySQL DATETIME field - which I think is what you want - you can use FROM_UNIXTIME():

INSERT INTO tablename (fieldname) VALUES (FROM_UNIXTIME('1234567890'));

RESOLVED IT:

DID

$posttime = time();

INSERT INTO tablename (fieldname) VALUES ($posttime));

If you just want to save the actual timestamp to the database you can just use the mysql function NOW() for that:

INSERT INTO tablename SET timefieldname = NOW():

You can than read that timestamp from the database and use the function to convert the diffrence to something like "30 minutes ago".

Or, if you want MySQL (instead of your code) to call the C-library function (time_t) time( ), have a look at the MySQL function UNIX_TIMESTAMP( ) as a way to give FROM_UNIXTIME( ) its argument.

The return value of UNIX_TIMESTAMP( ) fits perfectly in an INTEGER(10) field.