How do you convert a DATETIME time string from a user's time zone to GMT in CakePHP?
I'm aware of CakeTime
and TimeHelper
: They seem to handle converting time strings from server time to a user's local time very well, but they don't seem to cover dates that users submit. In one of my models, I've got a user-submitted time field that accepts input in DATETIME format, user's local time: 2014-04-07 04:48:05
. I need to convert this to UTC after the form is submitted.
This is my controller method for my view. I'm trying to use CakeTime::format to convert the sighted
field to UTC, but it moves the time the right number of hours in the wrong direction: Instead of converting 15:00EST to 19:00GMT, it converts it to 11:00 on save (!?).
How do I convert it from local time to GMT using proper PHP time zones?
public function add() {
App::uses('CakeTime', 'Utility');
if ($this->request->is('post')) {
$this->Post->create();
// Change the submitted time to UTC before the post saves
$this->request->data('Post.sighted', CakeTime::format($this->request->data['Post']['sighted'], '%Y-%m-%d %H:%M:%S', 'UTC'));
if ($this->Post->save($this->request->data)) {
$this->redirect(array('action' => 'view', $this->Post->id));
} else {
$this->Session->setFlash(__('The post could not be saved. Please, try again.'), 'flash/error');
}
}
// Get local time and set the field before the view loads
$this->request->data['Post']['sighted'] = CakeTime::format(date('Y-m-d H:i:s'), '%Y-%m-%d %H:%M:%S', 'N/A', 'America/New_York');
}