Set Timezone for getDate PHP function

When I went to set the timezone for use with the getDate function in PHP today, I couldn’t fine documentation for exactly that so I used what I did find to piece together the correct way to set a timezone within a PHP script for the getDate function. Here is how:

Example PHP Code:

<?php

//Set timezone:
date_default_timezone_set(‘America/New_York’);

//format date:
$start = getdate();
$smon = $start[‘mon’];
$sday = $start[‘mday’];
$syear = $start[‘year’];
$shr = $start[‘hours’];
$smin = $start[‘minutes’];
$ssec = $start[‘seconds’];

$formatted_date =  “$smon-$sday-$syear”.”_”.”$shr-$smin-$ssec”;

echo $formatted_date;

?>

The above PHP code will output:

 6-2-2014_11-24-23

For June, 2nd 2014 at 11:24:23am

By the way, the above format, 6-2-2014_11-24-23, I use for file names in applications that save data to a .txt file so I know when the file was saved by the PHP application and also so the file name will always be unique(as  long as it doesn’t run faster than one per second in which case you will need to use milliseconds). Of course, you may change the format in the code above to format your date/time however you like.

List of U.S. Timezones to use with date_default_timezone_set function:

Eastern ........... America/New_York
Central ........... America/Chicago
Mountain .......... America/Denver
Mountain no DST ... America/Phoenix
Pacific ........... America/Los_Angeles
Alaska ............ America/Anchorage
Hawaii ............ America/Adak
Hawaii no DST ..... Pacific/Honolulu

Leave a Reply

Your email address will not be published. Required fields are marked *