如何在CakePHP中将DATETIME时间字符串从用户的时区转换为 GMT?
我知道CakeTime
和TimeHelper
:他们似乎处理时间字符串从服务器时间转换为用户当地时间,但他们并没有。似乎涵盖了用户提交的日期。在我的某个模型中,我有一个用户提交的时间字段,该字段接受DATETIME格式的输入,即用户的本地时间:2014-04-07 04:48:05
。我需要在提交表单后将其转换为UTC。
这是我的视图的控制器方法。我尝试使用CakeTime :: format将sighted
字段转换为UTC,但它会将时间向正确的时间移动到错误的方向:而不是将15:00EST转换为19:00GMT,它会在保存(!?)时将其转换为11:00。
如何使用正确的PHP时区将其从本地时间转换为GMT?
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');
}
答案 0 :(得分:1)
如果您了解MVC和OOP基础知识,那么您无法在模型层中使用帮助程序。致命错误告诉您,您只是尝试访问一个不存在的对象,因为没有实例化此类对象。
检查API也有帮助: http://api.cakephp.org/2.4/source-class-CakeTime.html#1006
官方文件中也提到了这一点: http://book.cakephp.org/2.0/en/core-utility-libraries/time.html#CakeTime::format
doc块中的第四个示例显示了如何使用时区。
CakeTime::format('2012-02-15 23:01:01', '%c', 'N/A', 'America/New_York');
-
/**
* Returns a formatted date string, given either a UNIX timestamp or a valid strtotime() date string.
* This function also accepts a time string and a format string as first and second parameters.
* In that case this function behaves as a wrapper for TimeHelper::i18nFormat()
*
* ## Examples
*
* Create localized & formatted time:
*
* {{{
* CakeTime::format('2012-02-15', '%m-%d-%Y'); // returns 02-15-2012
* CakeTime::format('2012-02-15 23:01:01', '%c'); // returns preferred date and time based on configured locale
* CakeTime::format('0000-00-00', '%d-%m-%Y', 'N/A'); // return N/A becuase an invalid date was passed
* CakeTime::format('2012-02-15 23:01:01', '%c', 'N/A', 'America/New_York'); // converts passed date to timezone
* }}}
*
* @param integer|string|DateTime $date UNIX timestamp, strtotime() valid string or DateTime object (or a date format string)
* @param integer|string|DateTime $format date format string (or UNIX timestamp, strtotime() valid string or DateTime object)
* @param boolean|string $default if an invalid date is passed it will output supplied default value. Pass false if you want raw conversion value
* @param string|DateTimeZone $timezone Timezone string or DateTimeZone object
* @return string Formatted date string
* @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#TimeHelper::format
* @see CakeTime::i18nFormat()
*/