tags:

views:

148

answers:

4
+1  Q: 

datetime in php

i am devloping a quiz site and there is time for x min to answer the quiz. So when user clicks on start quiz link the starttime(current time at this instant )is recored in session .Also the endtime (start_time+ 30 min ) is recored in session and every time he submits a answer the current time is compared with the quiz end time. Only if the current time is less then end_time the answer shold be accepted.

  1. So how can i get the currentdatetime?
  2. How can i add x minutes tocurrent this datetime?
  3. How can i comapare (<=) datetime ?

I think we should use date time. Is it right?

+4  A: 

PHP measures time as seconds since Unix epoch (1st January 1970). This makes it really easy to work with, since everything just a single number.

To get the current time, use: time()

For basic maths like adding 30 minutes, just convert your interval into seconds and add:

time() + 30 * 60  // (30 * 60 ==> 30 minutes)

And since they're just numbers, just do regular old integer comparison:

$oldTime = $_SESSION['startTime'];
$now = time();

if ($now < $oldTime + 30 * 60) {
    //expired
}

If you need to do more complicated things like finding the date of "next tuesday" or something, look at strtotime(), but you shouldn't need it in this case.

nickf
A: 
  1. Use the time() function to get a UNIX timestamp, which is really just a large integer.
  2. The number returned by time() is the number of seconds since some date (like January 1, 1970), so to add $x minutes to it you do something like (time() + ($x*60)).
  3. Since UNIX timestamps are just numbers, you can compare them with the usual comparison operators for numbers (< <= > >= ==)
yjerem
A: 

time() will give you the current time in seconds since 1/1/1970 (an integer), which looks like it should be good.

To add x minutes, you'd just need to add x*60 to that, and you can compare it like any other two integers.

Source: http://us3.php.net/time

Dan G
+1  A: 

use php builtin functions to get time:

 <?php
     $currentTimeStamp = time(); // number of seconds since 1970, returns Integer value
     $dateStringForASpecificSecond = date('Y-m-d H:i:s', $currentTimeStamp);
 ?>

for your application that needs to compare those times, using the timestamp is more appropriate.

<?php
     $start = time();
     $end = $start + (30 * 60); // 30 minutes
     $_SESSION['end_time'] = $end;
?>

in the page where the quiz is submitted:

<?php
    $now = time();
    if ( $now <= $_SESSION['end_time'] ) {
         // ok!
    }
?>
farzad