0

Hello I have a vote system.

Once a person votes, I have column named "nextVote".

That column will hold the date when the user can vote again. By that column, I will be able to echo how many hours/minutes he needs to wait before voting.

That's my try:

    public final function setNextVote($ip)
    {
        $this->insert = $this->pdo->prepare("UPDATE auths SET nextVote = NOW() + INTERVAL 12 HOUR WHERE voter_ip = :ip");
        $this->insert->execute(array(":ip" => $ip));
    }

And that what it stores:

2013-05-14 05:56:24

Why?..

What I am trying to do is: Current time + 12 hours.

If today is 2013, 05, 14 and 12:00.

In 12 hours it would be

2013, 05, 14, 24:00 Why doesn't it do that?

    public function getTimeLeft($ip)
    {
        $this->get = $this->pdo->prepare
        ("
            SELECT TIMESTAMPDIFF(MINUTE, `nextVote`, NOW())
            FROM auths
            WHERE `voter_ip` = :ip
        ");
        $echo = $this->get->execute(array(":ip" => $ip));

        return $echo;
    }
4

3 回答 3

1

The problem is that you are expecting a result in the local timezone. MySQL uses the system timezone by default to produce a timestamp when calling NOW() or any other time/date related functions.

You can change the timezone on the server by passing the --timezone parameter to MySQL as described here.

However, the timezone is not relevant for your application, because you're only interested in relative time. Users of your application could possibly be in any timezone, so there's no point to assuming a specific one.

于 2013-05-13T15:04:45.710 回答
1

Your database looks to be using GMT, you can change the timezone on the database, but that can be difficult on a production machine if other things are using it. It should fix the problem tho. Or, try this

$date = date( 'Y-m-d H:i:s', strtotime( 'now +12 hours' ) );
$sql = "UPDATE auths SET nextVote = '{$date}' WHERE voter_ip = :ip";

if you want to update your timezone ( and are on ubuntu ), run dkpg-reconfigure tzdata

于 2013-05-13T15:05:06.547 回答
0

If you want the next date to be on the day's boundary... As opposed to 12 hours from now to the minute -- you can wrap a DATE() around your date math result, which will trim it to just the date for a datetime field.

UPDATE auths SET nextVote = DATE(DATE_ADD(NOW(), INTERVAL 1 DAY)) WHERE voter_ip = :ip
于 2013-05-13T15:08:52.380 回答