Php code to Get time and date for specific GMT time zone

No matter the server is in which GMT time zone here is extremely easy way to get time and date for any time zone. This is done with time() and gmdate() function. gmdate() funtion normally give us GMT time but by doing a trick with time() function we can get GMT+N or GMT-N means we can get time for any GMT time zone.

For example you have to get time for GMT+5 we will do it like following
$offset=5*60*60; //converting 5 hours to seconds.
$dateFormat="d-m-Y H:i";
$timeNdate=gmdate($dateFormat, time()+$offset);
?>

Now if you have to get the time which is GMT-5 now we will just subtract the offset from the time() instead of adding into time like in following example we are getting time for GMT-4

$offset=4*60*60; //converting 5 hours to seconds.
$dateFormat="d-m-Y H:i";
$timeNdate=gmdate($dateFormat, time()-$offset);
?>


Now finally the $timeNdate variable will be having the date and time in given format, which can be used to display or do anything with it.

Posted in |