简体   繁体   中英

Is it past a calculated time & date?

I've got to do a check if it's already past a certain time and date. Normally this would be easy for me, but the time that has to be checked is half an hour prior to the time I actually get from the database.

Let's say the database says: "2014-01-16" and "20:00". In this case I'd have to check if it's already past "21:30" on the 16th of januari 2014.

I have some code working for me now but it only says it's past that date if both the date and time have been passed (let's say it's the day after so it's obviously passed, it also has to be past 21:30 for it to say so).

Here is the code I have so far:

// Get the date today and date of the event to check if the customer can still buy tickets
$dateToday = strtotime(date('Y-m-d'));
// $details['Datum'] == 2014-01-15
$dateStart = strtotime($details['Datum']);

// Check if it's half an hour before the event starts, if so: don't sell tickets
$timeNow = strtotime(date('H:i'));
// $details['BeginTijd'] == 20:00
$substrStart = substr($details['BeginTijd'], 0, 5);
$startTimeHalfHour = strtotime($substrStart) - 1800;

if($timeNow > $startTimeHalfHour && $dateToday >= $dateStart) {
    // It's past the given time limit
    $tooLate = true;
} else {
    // There's still time
    $tooLate = false;
}

As you can see, it requires both the time and date to be past the given limits. In this example, if it's past the 15th it should set $tooLate to true, or if it's past 21:30 on the 15th.

It's best to convert DateTime strings to Unix timestamps for comparisons like this. This can be done with the DateTime class. Example:

$dateToday = new DateTime();
$date = new DateTime('2014-01-16 20:00');
// Adds an hour to the date.
$date->modify('+ 1 hour');

if ($dateToday > $date) {
  // Do stuff.
}

You could use strtotime("+30 minutes") to get the time in 30 minutes.

So assuming that $startTime is the time (unix time) the event starts, you could do

$current = strtotime("+30 minutes");

if($current > $startTime){
$tooLate = true;
}
else{
$tooLate = false;
}

By the way, lines like $dateToday = strtotime(date('Ym-d')); don't make much sense. Writing $dateToday = time(); has the same result.

strtotime() gives you aa Unix timestamp (number of seconds since 1970). time() also does.

To generate $startTime (the time the show starts at), you should take the full date and time string (eg. 2014-01-15 18:10:00 ) and pass it to strtotime . It will convert it to a Unix time.

If what you want is the time of the event minus 30 minutes, you could write:

$maxTime = strtotime("-30 minutes",$startTime); //where $startTime is the start time of the event, in Unix time.

Source: http://il1.php.net/strtotime

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM