Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validating timezone 'name' coming in from different site?

Tags:

timezone

php

i've got users coming in from a different site and i'm getting that site to send across their timezone in a standard 'tz' format

 Antarctica/Casey    Antarctica/Davis   
 Antarctica/DumontDUrville  Antarctica/Macquarie 
 Antarctica/Mawson  Antarctica/McMurdo

How do i verify that this 'string' coming in is a VALID timezone entry?


this is what i'm doing

        $script_tz = date_default_timezone_get();
        if(!date_default_timezone_set($specifiedTimeZone))
        {
            date_default_timezone_set($script_tz);
            $errormessage = "Invalid TimeZone";
            return;         
        }
        date_default_timezone_set($script_tz);

but i dont like it - seems kludgy.


testing it out:

Test1

$test1 = 'America/New_York';
$test2 = 'junk';

$start = microtime(true);
for($i=1;$i<10000;$i++)
{
    if (in_array($test1, DateTimeZone::listIdentifiers())) {}else {}
    if (in_array($test2, DateTimeZone::listIdentifiers())) {}else {}
}

$end = microtime(true);

echo $end-$start;
?>

9.7208099365234

Test2

<?php

$test1 = 'America/New_York';
$test2 = 'junk';

error_reporting(0);
$start = microtime(true);
for($i=1;$i<10000;$i++)
{
        $script_tz = date_default_timezone_get();
        if(!date_default_timezone_set($test1))
        {
                date_default_timezone_set($script_tz);
        }
        else
                date_default_timezone_set($script_tz);
        $script_tz = date_default_timezone_get();
        if(!date_default_timezone_set($test2))
        {
                date_default_timezone_set($script_tz);
        }
        else
                date_default_timezone_set($script_tz);
}


$end = microtime(true);

echo $end-$start;
?>

0.25762510299683
like image 364
siliconpi Avatar asked Apr 18 '11 13:04

siliconpi


1 Answers

use DateTimeZone::listIdentifers()

if (in_array($timezone, DateTimeZone::listIdentifiers())) {
    echo "valid";
}
else {
    echo "invalid";
}
like image 179
Jacob Avatar answered Nov 19 '22 06:11

Jacob