日時の値を指定の形式にフォーマット(date_format)

広告

「date_format」は日時の値を指定の形式にフォーマットします。日時の値は予約変数の{$smarty.now}が返す値であるUnixタイムスタンプの形式などで指定します(他にも認識できる日付の形式はあります)。書式は次の通りです。

{$変数名|date_format[:フォーマット文字列]}

1番目のパラメータでフォーマット形式を表すフォーマット文字列を指定します。フォーマット文字列を指定しなかった場合は「%b %e, %Y」がデフォルトの値として使用されます。フォーマット文字列はPHPの「strftime」関数で使用するものと同じです。詳しくは「指定の形式にフォーマットされた日時を取得(strftime)」を参照して下さい。

また2番目のパラメータで対象の値が空のときのデフォルトの日付を指定することが出来ます。

{$変数名|date_format[:フォーマット文字列[:デフォルトの日付]]}

具体的には次のように記述します。

{$dateval|date_format:"%Y / %m / %d"}
{$dateval|date_format:"%H:%M:%S"}

サンプルプログラム

では簡単なサンプルプログラムを作成して試してみます。

sample13-1.php

<?php

require_once('Smarty.class.php');

$smarty = new Smarty();

$smarty->template_dir = 'd:/smartysample/modifier/templates/';
$smarty->compile_dir  = 'd:/smartysample/modifier/templates_c/';
$smarty->config_dir   = 'd:/smartysample/modifier/configs/';
$smarty->cache_dir    = 'd:/smartysample/modifier/cache/';

$smarty->assign('title', '修飾子のテスト');

$smarty->display('sample13-1.tpl');

?>

上記を「sample13-1.php」の名前で「(Apacheドキュメントルート)¥smarty¥modifier」に保存します。

sample13-1.tpl

{* Smarty modifier/sample13-1.tpl *}
<html>
<head>
<title>Smarty Test</title>
</head>
<body>

<h1>{$title}</h1>
<p>{$smarty.now|date_format:"%Y / %m / %d"}</p>
<p>{$smarty.now|date_format:"%H:%M:%S"}</p>

</body>
</html>

上記を「sample13-1.tpl」の名前で「D:¥smartysample¥modifier¥templates」に保存します。

そしてブラウザから「http://localhost/smarty/modifier/sample13-1.php」へアクセスして下さい。

日時の値を指定の形式にフォーマット(date_format)

( Written by Tatsuo Ikura )