UTC to local timezone in PHP
Today we will talk about how you can convert the UTC time to your local timezone in PHP. If you are doing server side rendering and want to get the user’s timezone in PHP, you can get it by first saving the timezone in session via AJAX. Because timezone can be get from client side, so we will call an AJAX from client side and pass the timezone in it.
const ajax = new XMLHttpRequest();
ajax.open("POST", "/set-timezone", true);
const formData = new FormData();
formData.append("_token", "{{ csrf_token() }}");
formData.append("time_zone", Intl.DateTimeFormat().resolvedOptions().timeZone);
ajax.send(formData);
Then create a function in PHP that will handle this request.
public function set_timezone()
{
$time_zone = request()->time_zone ?? "";
if (!empty($time_zone))
{
session()->put("time_zone", $time_zone);
return response()->json([
"status" => "success",
"message" => "Timezone has been set."
]);
}
}
We are saving it in session because timezone will be different for each user. Once the timezone is saved in session, you can convert any datetime from UTC to your local timezone. For example, in following code we are converting the current date and time from UTC to my timezone:
public function get_timezone()
{
$time_zone = session()->get("time_zone", "");
if (!empty($time_zone))
{
date_default_timezone_set($time_zone);
}
$utc_time = now()->utc();
$time = date("d F, Y h:i:s a", strtotime($utc_time . " UTC"));
return $time;
}
So that’s how you can convert the UTC time to your local timezone in PHP. If you want to know how to convert it using Node.js or Python, you can check our tutorials on them.