js時間格式化函數(兼容IOS)

 * 時間格式化
    * @param  {Object} dateObj 時間對象
    * @param  {String} fmt 格式化字符串
    */
   dateFormat(dateObj, fmt) {
     let date;
     if (this.isString(dateObj))
     {
       date = this.strToDate(dateObj)
     } else if (this.isDate(dateObj))
     {
       date=dateObj
     }
     else{
       return ""
     }
     var o = {
       "M+": date.getMonth() + 1, //月份         
       "d+": date.getDate(), //
       "h+": date.getHours() % 12 == 0 ? 12 : date.getHours() % 12, //小時         
       "H+": date.getHours(), //小時         
       "m+": date.getMinutes(), //
       "s+": date.getSeconds(), //
       "q+": Math.floor((date.getMonth() + 3) / 3), //季度         
       "S": date.getMilliseconds() //毫秒         
     };
     var week = {
       "0": "日",
       "1": "一",
       "2": "二",
       "3": "三",
       "4": "四",
       "5": "五",
       "6": "六"
     };
     if (/(y+)/.test(fmt)) {
       fmt = fmt.replace(RegExp.$1, (date.getFullYear().toString() + "").substr(4 - RegExp.$1.length));
     }
     if (/(E+)/.test(fmt)) {
       fmt = fmt.replace(RegExp.$1, ((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? "星期" : "周") : "") + week[date.getDay().toString() + ""]);
     }
     for (var k in o) {
       if (new RegExp("(" + k + ")").test(fmt)) {
         fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k].toString()) : (("00" + o[k].toString()).substr(("" + o[k].toString()).length)));
       }
     }
     return fmt;
   }
 /**
     * 字符串轉換爲時間
     * @param  {String} src 字符串
     */
    strToDate(dateObj){
      dateObj = dateObj.replace(/T/g, ' ').replace(/\.[\d]{3}Z/, '').replace(/(-)/g, '/')
      if (dateObj.indexOf(".")>0)dateObj = dateObj.slice(0, dateObj.indexOf("."))

     return new Date(dateObj)
    }

使用方法:

第一個參數是個obj對象,當前只能是時間對象或者是時間字符串

第二個參數是格式化字符串,和C# 格式化規則一樣,除了周的格式化,這裏使用了'E'來格式化周幾

這裏是頁面調用例子:

app.Tools.dateFormat("yyyy/MM/dd") 結果 2017/07/19

app.Tools.dateFormat("yyyy/MM/dd HH:mm:ss") 結果 2017/07/19 10:09:11

app.Tools.dateFormat("yyyy/MM/dd EE HH:mm:ss") 結果 2017/07/19 週三 10:09:11

其他的就不一一舉例了,可以參考C#格式化的標準

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章