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

来源:互联网 发布:已为关闭蜂窝移动数据 编辑:程序博客网 时间:2024/04/29 09:32

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

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

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

 

php文件:

  1. <?php  
  2.   
  3.   //导入自定义smarty操作类SmartyInit.php  
  4.   include_once('class/SmartyInit.php');  
  5.   $smarty = new SmartyInit();  
  6.     
  7.   //设置默认时区为上海  
  8.   date_default_timezone_set('Asia/Shanghai');  
  9.   //输出echo strtotime('now'),结果如:1245763672  
  10.   //可知strtotime('now')返回的是时间戳  
  11.   
  12.   //也可是从数据库得到的时间戳  
  13.   $time = time();  
  14.   
  15.   echo 'php格式化输出:<br />';  
  16.   echo '昨天:'.date('Y-m-d H:i:s'strtotime('-1 day')).'<br />';  
  17.   //date('Y-m-d H:i:s'),不写第二个参数,默认为当前时间  
  18.   //也可写为:date('Y-m-d H:i:s', strtotime('now'))  
  19.   echo '今天:'.date('Y-m-d H:i:s').'<br />';  
  20.   echo '明天:'.date('Y-m-d H:i:s'strtotime('1 day')).'<br />';  
  21.   echo '赋值时间戳:'.date('Y-m-d H:i:s'$time).'<br />';  
  22.   
  23.   //strtotime('today')只输出当天日期,  
  24.   //strtotime('today 00:00:00')可输出时间  
  25.   $smarty->assign('yesterday'strtotime('yesterday'));  
  26.   $smarty->assign('today'strtotime('today 20:15:04'));  
  27.   $smarty->assign('tomorrow'strtotime('tomorrow'));  
  28.     
  29.     
  30.   $smarty->assign('yesterday1'strtotime('-1 day'));  
  31.   //等同$smarty->assign('today1', strtotime('0 day'));  
  32.   $smarty->assign('today1'strtotime('now'));  
  33.   $smarty->assign('tomorrow1'strtotime('1 day'));  
  34.   $smarty->assign('time'$time);  
  35.     
  36.   $smarty->display('index.html');  

 模板文件(html):

  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  2. <html xmlns="http://www.w3.org/1999/xhtml">  
  3. <head>  
  4. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />  
  5. <title>smarty测试-www.jbxue.com</title>  
  6. </head>  
  7.   
  8. <body>  
  9.   
  10. <p>smarty模板输出:<br />  
  11. 昨天:<{$yesterday|date_format:'%Y-%m-%d %H:%M:%S'}>  
  12. <br />  
  13. 今天:<{$today|date_format:'%Y-%m-%d %H:%M:%S'}>  
  14. <br />  
  15. 明天:<{$tomorrow|date_format:'%Y-%m-%d %H:%M:%S'}>  
  16. </p>  
  17. <p>  
  18. 昨天:<{$yesterday1|date_format:'%Y-%m-%d %H:%M:%S'}>  
  19. <br />  
  20. 今天:<{$today1|date_format:'%Y-%m-%d %H:%M:%S'}>  
  21. <br />  
  22. 明天:<{$tomorrow1|date_format:'%Y-%m-%d %H:%M:%S'}>  
  23. <br />  
  24. 赋值时间戳:<{$time|date_format:'%Y-%m-%d %H:%M:%S'}>  
  25. </p>  
  26.   
  27. smarty保留变量输出:<{$smarty.now|date_format:"%Y-%m-%d %H:%M:%S"}>  
  28. </body>  
  29. </html>  

 运行结果:

时间格式化输出

0 0
原创粉丝点击