zoukankan      html  css  js  c++  java
  • 微信小程序时间格式化总结

    时间格式化,这个问题在很多项目中都会遇到,后端返回的时间格式一般都是一致的,而前端的展示可能是2021年3月12日 15:00:00或者2021-03-12 15:00:00 亦或者是2021.03.12 15:00:00等等,这就需要前端根据UI需要展示,看到很多人是直接处理该字段的值,例如obj.startTime = moment(obj.startTime).format('YYYY-MM-DD HH:mm:ss')。个人认为这是字段展示的不同形式,没有必要改变该字段,而是应该使用filter,格式化数据的展示。

    然而在小程序里 ios真机上不支持 2020-06-28 00:00:00这种时间格式, 必须转成2020/06/28 00:00:00 再进行格式化。

    因此根据以上总结,小程序时间格式化的写法有:

     1 // 时间格式过滤器
     2 Vue.filter('formatDate', function (time, fmt) {
     3   // 有些数据后端没有处理格式如 2021-03-01 00:00:00.0
     4   time = time.replace('.0', '');
     5   let value = time && time.replace(/-/g, '/');
     6   let getDate = new Date(value);
     7   let o = {
     8    'M+': getDate.getMonth() + 1,
     9    'd+': getDate.getDate(),
    10    'h+': getDate.getHours(),
    11    'm+': getDate.getMinutes(),
    12    's+': getDate.getSeconds(),
    13    'q+': Math.floor((getDate.getMonth() + 3) / 3),
    14    'S': getDate.getMilliseconds()
    15   };
    16   if (/(y+)/.test(fmt)) {
    17    fmt = fmt.replace(RegExp.$1, (getDate.getFullYear() + '').substr(4 - RegExp.$1.length))
    18   }
    19   for (let k in o) {
    20    if (new RegExp('(' + k + ')').test(fmt)) {
    21     fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
    22    }
    23   }
    24   return fmt;
    25  });

    页面上的使用方法是:

     <div class="info-item">
              {{ item.startDate | formatDate('yyyy年MM月dd日') }}~{{ item.endDate | formatDate('yyyy年MM月dd日') }}
            </div>
    <div class="date f24">有效期: {{ item.startDate | formatDate('yyyy.MM.dd') }}~{{ item.endDate | formatDate('yyyy.MM.dd') }}</div>

    这样就可以根据页面UI随意展示时间格式,而非每个字段自己处理一遍。

    开心写代码,愉快工作~多多指教

  • 相关阅读:
    其他魔术方法
    类型约束和类的魔术常量
    PHP对象遍历、内置标准类与数据转对象
    类的自动加载与对象的克隆
    PHP重载与接口
    面向对象
    PHP基础
    地下城与勇士的项目整理
    mysql建表
    jQuery
  • 原文地址:https://www.cnblogs.com/scuplting-in-time/p/14524536.html
Copyright © 2011-2022 走看看