Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle differences between server time and users local time?

I'm in the process of developing a web application targeting other countries.

Now, to illustrate my thoughts, I was thinking something like this:

// Illustrates the current time on my server
$time = new DateTime();
echo $time->format("Y-m-d H:i:s P");

// Illustrates the current time for the time the user told my app he is in
$time = new DateTime(null, new DateTimeZone('Europe/London'));
echo $time->format("Y-m-d H:i:s P");

The output of this is:

2012-11-30 11:02:40 +01:00 // My server time
2012-11-30 10:02:40 +00:00 // The users time

It's all very fine, because I can now present the current time for the user. But what I need is to get the user input and have it translated to my servers time - or at least I think this is the right way to do it.

A use case
User in London tells my application that he needs an action performed at 2012-12-01 19:00:00. By updating this timestamp in my database, my cronjob will perform this action at the specified time. But my user will experience this as happening at 2012-12-01 18:00:00 instead.

While thinking of a way to solve this, I was working with some offset hours and this just gave me a lot of spaghetti code and some messed up table designs for my database.

How do I pull this off so that it makes sense?

like image 276
Repox Avatar asked Dec 02 '25 15:12

Repox


1 Answers

You can alter the timezone of the DateTime object to the required. If you have the user's specfied date time from their timezone you can easily do a conversion.

 $time = new DateTime(null, new DateTimeZone('Europe/London'));
 echo $time->format("Y-m-d H:i:s P");

 $time->setTimezone(new DateTimeZone('America/Chicago'));
 echo $time->format("Y-m-d H:i:s P");
like image 144
Kami Avatar answered Dec 04 '25 07:12

Kami



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!