- 2008-08-13 (水) 21:30
カレンダー・スケジュールに関するアプリを作っている関係上、どうしても日付に関する処理が多くなってしまいます。
DBに保存した日付値を任意のフォーマットに変換してくれるコンポーネントやヘルパーがデフォルトで用意されていないか探してみたのですが見つからない…。
多分、Timeヘルパーあたりにあると思うのですが、ヘルパーだとController内で使用することが出来ないので「DatetimeComponent」なるコンポーネントを自作してみました。
componentsフォルダにdatetime.phpファイルを作成し、下記のソースをコピペ。
・app/controllers/components/datetime.php
[sourcecode language='php']
class DatetimeComponent extends Object
{
var $controller = null;
function __construct(){
parent::__construct();
}
function startup(&$controller){
$this->controller =& $controller;
}
function toFormat($elem, $format){
//2008-02-27 00:00:00
$set_year = substr($elem, 0, 4); //年
$set_month = substr($elem, 5, 2); //月
$set_day = substr($elem, 8, 2); //日
$set_hour = substr($elem, 11, 2); //時
$set_minute = substr($elem, 14, 2); //分
$set_second = substr($elem, 17, 2); //秒
return date($format, mktime($set_hour, $set_minute, $set_second, $set_month, $set_day, $set_year));
}
}
?>
[/sourcecode]
フォーマットの指定はPHPの標準関数であるDate関数と同じ形式です。
↓こんな感じで使用します。
[sourcecode language='php']
$yyyy_m_d = $this->Datetime->toFormat($this->data['Schedule']['start'],’Y/n/j’);
[/sourcecode]
- 次へ: basics.php – stripslashes_deep($value) (CakePHP解析 #10)
- 前へ: dispatcher.php – $this->parseParams($url) (CakePHP解析 #9)
コメント:0
トラックバック:0
- このエントリーへのトラックバックURL
- http://www.studio-kingdom.com/cakephp/cakephp_training/77/trackback