1

I've got a redirect script meant to not redirect between certain times. I'm using Date("G"), but if I use this for say 12:30, it won't work because I believe 030 is read as 0 and not 30. Will a seperate statement like if $hour = 0 {$hour = $hour + 1} and then writing $milTime as 130 work? If so, is this the best way? If not, what will work?

Here's an example of a time block that won't read correctly.

<?php
date_default_timezone_set('America/Los_Angeles');
        $hour = date("G");
        $min = date("i");
        $milTime = $hour . $min ;

        if($milTime < 030 || $milTime > 045)
        {
        header('Location: http://havetowatchit.com/watchit.php');
        exit();
        }
?> 
TSpinVirus
  • 41
  • 2
  • 1
    In php, integers starting with `0` are considered octal. So `030` is really `24` and `045` is really `37`. You would likely want to convert the number to something like "seconds (or minutes) into the day" and compare with that. Or use a proper timestamp or even a date/time object. – Jonathan Kuhn Oct 23 '15 at 17:35
  • 1
    Also, just do `$milTime = date("Gi");` – AbraCadaver Oct 23 '15 at 17:37
  • I had no idea about that. Ok, so I can just convert to octal and all is well. Thanks @JonathanKuhn – TSpinVirus Oct 23 '15 at 17:46
  • I would suggest just getting a timestamp for the suggested date/time you want to look for. It is simple with strtotime. `$time = time(); if($time < strtotime('0030') || $time > strtotime('0045')){ /* do something */ }` – Jonathan Kuhn Oct 23 '15 at 17:47
  • Thanks @AbraCadaver I had no idea that would work! – TSpinVirus Oct 23 '15 at 17:48
  • @JonathanKuhn I've been reading all I can about strtotime, but I don't think I'm ready to use it. It's over my head, thanks though. – TSpinVirus Oct 23 '15 at 17:59
  • You pass in a string that represents a date and or time and it returns a unix timestamp. The timestamp is just the number of seconds since `1-Jan-1970 00:00:00`. – Jonathan Kuhn Oct 23 '15 at 18:00

1 Answers1

0

You just have to get rid of your leading zeroes. As mentioned above, numbers starting with zero are interpreted as octal. But with PHP's dynamic typing, string "030" (half past midnight) can be treated numerically as 30:

$ php -a
Interactive shell

php > $time = "030";
php > var_dump($time < 40);
bool(true)
php > var_dump($time > 20);
bool(true)
php > var_dump($time > 40);
bool(false)

So your code can look like this:

<?php
    date_default_timezone_set('America/Los_Angeles');
    $time = date("Gi");
    if($time < 30 || $time > 45) {
        header('Location: http://havetowatchit.com/watchit.php');
        exit();
    }
?>
Community
  • 1
  • 1
miken32
  • 42,008
  • 16
  • 111
  • 154