Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
  • How to Set Timezone in CakePHP 3?

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 1
    • 0
    • 5.22k
    Comment on it

    Dealing and working with time zone "Date/Day, Time and Duration" of a Website and an App is the most common task or requirement, which is not as easy as seen, it can be little tricky as it compounded with a set of rules of timekeeping and calendar related data.


    So, In this tutorial, I will show you "How to Set Timezone in CakePHP 3".

    We usually specify the timezone in php.ini file but in CakePHP 3 it will overwrite the timezone in the bootstrap.php file.
    Therefore, to change the timezone to any other we need to make changes in bootstrap.php.



    Let's see the Steps:

    Step 1: In App/Config/bootstrap.php date_default_timezone_set('UTC'); is set by default, you just have to change it to your current timezone or anyone you want. I am using UTC "UTC is Universal Time Coordinated".


    Step 2: We use UTC to keep times in database in synchronized way. To do stuff like calculation and conversions, we can assume its base is UTC.

    On saving time to database, we have to convert our users' data which is based on their own timezone to UTC format, to keep our database synchronized.

    CakePHP 3 uses Cake\I18n\Time as the class for handling and functioning on time and timezone.


    For conversion use below code

    $timeForDatabase = (new Time($userInputTime, 'America/New_York'))->setTimezone('UTC');


    Step 3: While displaying the time from our database to the users, we convert it back to user's timezone.

    Like shown below:

    $timeForUser = $timeFromDatabase->setTimezone('America/New_York');

    CakePHP 3 ORM return Cake\I18n\Time instance for DateTime columns. So we don't need to instantiate it.




    This is how the work is done on timezone in the latest version of CakePHP i.e CakePHP 3.

    Hope you all got the basic idea of how to set timezones. For any questions feel free to post in the comment section below.

    How to Set Timezone in CakePHP 3?

 0 Comment(s)

Sign In

Sign up using

Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: