user220755
user220755

Reputation: 4446

The time function in php and 1969

I am trying to save the time in the database for when a user add an entry. Every time I run the time() function it prints (or returns) 1277155717 which represents 1969.

I was wondering if there is a way to save the time to the database in a way that it represents the actual date today at this moment.

I am using the function

/* Works out the time since the entry post, takes a an argument in unix time (seconds) */
function time_since($original) {
    // array of time period chunks
    $chunks = array(
        array(60 * 60 * 24 * 365 , 'year'),
        array(60 * 60 * 24 * 30 , 'month'),
        array(60 * 60 * 24 * 7, 'week'),
        array(60 * 60 * 24 , 'day'),
        array(60 * 60 , 'hour'),
        array(60 , 'minute'),
    );

    $today = time(); /* Current unix time  */
    $since = $today - $original;

    // $j saves performing the count function each time around the loop
    for ($i = 0, $j = count($chunks); $i < $j; $i++) {

        $seconds = $chunks[$i][0];
        $name = $chunks[$i][1];

        // finding the biggest chunk (if the chunk fits, break)
        if (($count = floor($since / $seconds)) != 0) {
            // DEBUG print "<!-- It's $name -->\n";
            break;
        }
    }

    $print = ($count == 1) ? '1 '.$name : "$count {$name}s";

    if ($i + 1 < $j) {
        // now getting the second item
        $seconds2 = $chunks[$i + 1][0];
        $name2 = $chunks[$i + 1][1];

        // add second item if it's greater than 0
        if (($count2 = floor(($since - ($seconds * $count)) / $seconds2)) != 0) {
            $print .= ($count2 == 1) ? ', 1 '.$name2 : ", $count2 {$name2}s";
        }
    }
    return $print;
}

In order to display the number of minutes, years, months, etc since the comment was posted and it is returning (40 years, 6 months ago) when I pass the value of the function time();

Upvotes: 0

Views: 223

Answers (3)

Don Kirkby
Don Kirkby

Reputation: 56230

Be very careful before you start implementing your own date calculations. There are always weird cases to deal with. In your example, it looks to me like you aren't taking into account daylight savings time or leap years. I don't know if that matters to you.

Your chances are better if you use some library to do the date calculations for you. I would suggest you start by looking at the date_diff function in PHP. I don't know whether it handles daylight savings and leap years, but that's where I would start.

Upvotes: 0

cypher
cypher

Reputation: 6992

Why won't you just use sql's timestamp type, i.e.

INSERT INTO posts (content, created) VALUES ("Sample post", NOW());

Upvotes: 1

Ian P
Ian P

Reputation: 12993

Are you wanting a timestamp or the actual formatted time?'

If it's the latter, try this:

$time = date("h:i:s");

Upvotes: 0

Related Questions