helper.html 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. <!DOCTYPE HTML>
  2. <html>
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>helper-demo</title>
  6. <script src="../dist/template.js"></script>
  7. </head>
  8. <body>
  9. <h1>辅助方法</h1>
  10. <div id="content"></div>
  11. <script id="test" type="text/html">
  12. {{time | dateFormat:'yyyy年 MM月 dd日 hh:mm:ss'}}
  13. </script>
  14. <script>
  15. /**
  16. * 对日期进行格式化,
  17. * @param date 要格式化的日期
  18. * @param format 进行格式化的模式字符串
  19. * 支持的模式字母有:
  20. * y:年,
  21. * M:年中的月份(1-12),
  22. * d:月份中的天(1-31),
  23. * h:小时(0-23),
  24. * m:分(0-59),
  25. * s:秒(0-59),
  26. * S:毫秒(0-999),
  27. * q:季度(1-4)
  28. * @return String
  29. * @author yanis.wang
  30. * @see http://yaniswang.com/frontend/2013/02/16/dateformat-performance/
  31. */
  32. template.helper('dateFormat', function (date, format) {
  33. if (typeof date === "string") {
  34. var mts = date.match(/(\/Date\((\d+)\)\/)/);
  35. if (mts && mts.length >= 3) {
  36. date = parseInt(mts[2]);
  37. }
  38. }
  39. date = new Date(date);
  40. if (!date || date.toUTCString() == "Invalid Date") {
  41. return "";
  42. }
  43. var map = {
  44. "M": date.getMonth() + 1, //月份
  45. "d": date.getDate(), //日
  46. "h": date.getHours(), //小时
  47. "m": date.getMinutes(), //分
  48. "s": date.getSeconds(), //秒
  49. "q": Math.floor((date.getMonth() + 3) / 3), //季度
  50. "S": date.getMilliseconds() //毫秒
  51. };
  52. format = format.replace(/([yMdhmsqS])+/g, function(all, t){
  53. var v = map[t];
  54. if(v !== undefined){
  55. if(all.length > 1){
  56. v = '0' + v;
  57. v = v.substr(v.length-2);
  58. }
  59. return v;
  60. }
  61. else if(t === 'y'){
  62. return (date.getFullYear() + '').substr(4 - all.length);
  63. }
  64. return all;
  65. });
  66. return format;
  67. });
  68. // --------
  69. var data = {
  70. time: 1408536771253,
  71. };
  72. var html = template('test', data);
  73. document.getElementById('content').innerHTML = html;
  74. </script>
  75. </body>
  76. </html>