Reputation: 28843
I have built a simple Timezone helper for my CakePHP app using various examples here on Stack Overflow which saves the users zone against their user record. e.g. Europe/London.
To see the helper: http://pastebin.com/VGivwqHJ
When a user logs into the application, I save the date/time of when they logged in so that I can display a list of logs to the user for security reasons. e.g. $this->User->saveField('lastlogin', date('Y-m-d H:i:s'));
However that date will currently pull the server date/time. How can I make use of the timezone of the user to amend it?
I tried:
$date = new DateTime(null, new DateTimeZone($user['User']['timezone']));
and then: $this->User->saveField('lastlogin', $date->date);
but I just get null...
But if I debug $date I get for example:
object(DateTime) {
date => '2013-04-01 15:22:32'
timezone_type => (int) 3
timezone => 'Europe/London'
}
1.) What am I doing wrong? How do I pull the datetime from the object?
2.) Is this a good way to handle this? As it means I have to replace all date()
calls with this snippet to get the users time.
3.) Won't the dates on the website become mismatched so for example if a user in Europe posts something AFTER a user in the USA but because their local time was used it would display it as different, possibly look as though BEFORE the USA counterpart.
Should I instead SAVE the server time and then use the snippet above to display it differently to the user, so all times are the same timezone but then displayed relative to the user?
Upvotes: 3
Views: 720
Reputation: 146460
I'm not sure that you can save a DateTime
object right with saveField()
. You must probably convert it to string in the format that CakePHP believes to be universal:
$this->User->saveField('lastlogin', $date->format('Y-m-d H:i:s'))
Your original code is probably triggering this notice:
Notice: Undefined property: DateTime::$date
... because there's no date
public property in the DateTime class.
About your other questions, as you already point out you obviously cannot compare local times that belong to different time zones, just like you cannot compare kilometres with miles. If you store local times you need to store the time zone as well and make the conversion everytime. Thus it's simpler to just normalise dates and always store them with the same time zone (either UTC or the server's time zone) and perform the conversion when displaying the information. That also makes more sense because the local time of the post author is irrelevant for everybody else.
Upvotes: 2