`
crazymud
  • 浏览: 57500 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

php和smarty中格式化输出日期和时间的比较

    博客分类:
  • PHP
阅读更多

php中格式化输出日期和时间可用:date('Y-m-d H:i:s',时间戳); 的形式输出,对应的是“年-月-日 时:分:秒”。

而在smarty模板中,如$time是php文件中assign过来的时间戳,在模板文件中写法为:

<{$time|date_format:'%Y-%m-%d %H:%M:%S'}> ,同样对应的输出格式为:“年-月-日 时:分:秒”。

 

php文件:

<?php

  //导入自定义smarty操作类SmartyInit.php
  include_once('class/SmartyInit.php');
  $smarty = new SmartyInit();
  
  //设置默认时区为上海
  date_default_timezone_set('Asia/Shanghai');
  //输出echo strtotime('now'),结果如:1245763672
  //可知strtotime('now')返回的是时间戳

  //也可是从数据库得到的时间戳
  $time = time();

  echo 'php格式化输出:<br />';
  echo '昨天:'.date('Y-m-d H:i:s', strtotime('-1 day')).'<br />';
  //date('Y-m-d H:i:s'),不写第二个参数,默认为当前时间
  //也可写为:date('Y-m-d H:i:s', strtotime('now'))
  echo '今天:'.date('Y-m-d H:i:s').'<br />';
  echo '明天:'.date('Y-m-d H:i:s', strtotime('1 day')).'<br />';
  echo '赋值时间戳:'.date('Y-m-d H:i:s', $time).'<br />';

  //strtotime('today')只输出当天日期,
  //strtotime('today 00:00:00')可输出时间
  $smarty->assign('yesterday', strtotime('yesterday'));
  $smarty->assign('today', strtotime('today 20:15:04'));
  $smarty->assign('tomorrow', strtotime('tomorrow'));
  
  
  $smarty->assign('yesterday1', strtotime('-1 day'));
  //等同$smarty->assign('today1', strtotime('0 day'));
  $smarty->assign('today1', strtotime('now'));
  $smarty->assign('tomorrow1', strtotime('1 day'));
  $smarty->assign('time', $time);
  
  $smarty->display('index.html');

 模板文件(html):

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>smarty测试</title>
</head>

<body>

<p>smarty模板输出:<br />
昨天:<{$yesterday|date_format:'%Y-%m-%d %H:%M:%S'}>
<br />
今天:<{$today|date_format:'%Y-%m-%d %H:%M:%S'}>
<br />
明天:<{$tomorrow|date_format:'%Y-%m-%d %H:%M:%S'}>
</p>
<p>
昨天:<{$yesterday1|date_format:'%Y-%m-%d %H:%M:%S'}>
<br />
今天:<{$today1|date_format:'%Y-%m-%d %H:%M:%S'}>
<br />
明天:<{$tomorrow1|date_format:'%Y-%m-%d %H:%M:%S'}>
<br />
赋值时间戳:<{$time|date_format:'%Y-%m-%d %H:%M:%S'}>
</p>

smarty保留变量输出:<{$smarty.now|date_format:"%Y-%m-%d %H:%M:%S"}>
</body>
</html>

 运行结果:

时间格式化输出

 

  • SmartyInit.rar (612 Bytes)
  • 描述: 自定义smarty操作类SmartyInit.php
  • 下载次数: 13
  • index.rar (700 Bytes)
  • 描述: php文件index.php
  • 下载次数: 6
  • index.rar (500 Bytes)
  • 描述: 模板文件index.html
  • 下载次数: 4
3
1
分享到:
评论
1 楼 hnlixf 2011-08-08  

相关推荐

Global site tag (gtag.js) - Google Analytics