Thursday, 20 June 2013

TimeZone conversion using DateTime Class in PHP

Today, we are going to see, how to convert date and time from one TimeZone to another TimeZone in PHP. Before that. let me ask you the question. Why do you need to do this?

Let's say, you are developing a web application that will be accessed by globally. In your web application, users will be logged using the login page. In Home Page, you will be displaying the user Last Login Date and Time. User will be more comfortable to see the last login date and time in their timezone instead of server default timezone where it is located.

Let's say, your server is located in New York, So your timezone will be America/New_York.
date_default_timezone_set("America/New_York");
echo date('F jS, h:i A T', time());

This will return the date and time in America/New_York Timezone.

June 20th, 10:16 AM EDT

But, i am accessing your web application from India, so my timezone is Asia/Kolkata.

Now, we are going to see, how we can display the current date and time in Asia/Kolkata Timezone. This can be implemented using the DateTime and DateTimeZone Class.
$confTimezone = new DateTimeZone("Asia/Kolkata");
$datetime = date('Y-m-d H:i:s',time()); //this will contain date and time in America/New_York Timezone
$serverDateTime = new DateTime($datetime, $confTimezone); //return datetime instance in Asia/Kolkata Timezone
$CurrentTime = $serverDateTime->format('F jS, h:i A T');

Now, $CurrentTime will return the date and time in Asia/Kolkata Timezone.

June 20th, 10:22 AM IST

Hope, you enjoyed this Post.

2 comments:

  1. Thanks for this great post, and, nice explanations. Guess the best way is to have good content on your blog and the rest will follow, as the song sings...

    ReplyDelete