What is the scope of "date_default_timezone_set()" function

Viewed 127

I am using Laravel, and I have set the timezone "UTC" in the config/app.php file but I want to do the calculation in the "America/New York" timezone but if I use date_default_timezone_set() in any function then its scope will be for that particular function or it will be set for global scope

For e.g.

function xyz(){

date_default_timezone_set("America/New York");

}

If I set the date_default_timezone_set("America/New York"); inside this function, it's scope inside this function or globally for the whole application, if it's scope for whole the application how to make this scope inside the function only

Thanks

1 Answers

I bet, it's globally. You can preserve the timezone value so it's the same as before after the function call like this:

function xyz(){
    $tz = date_default_timezone_get();
    date_default_timezone_set("America/New York");
    // do stuff
    date_default_timezone_set($tz); // reset timezone to old value
}

If you want, you can encapsulate that into an own function:

function xyz(){
    temporary_timezone_transaction("America/New York", function() {
        // do stuff
    });
}

function temporary_timezone_transaction(string $temporaryTz, Callable $fn) {
    $globalTz = date_default_timezone_get();
    date_default_timezone_set($temporaryTz);
    call_user_func($fn);
    date_default_timezone_set($globalTz); // reset timezone to old value
}
Related