1. 程式人生 > >格式化時間相關函式

格式化時間相關函式

20180903 -> 2018-09-03
function formatStr(str,type){
    let i = 0,_type = type || "xxxx-xx-xx xx:xx:xx";
    return _type .replace(/x/g, () => { return str[i++]})
}
阿拉伯 轉 中文 101 -> 一百零一
function numToChina (value) {
   var that = this;
   var chnNumChar = ["零", "一", "二", "三", "四", "五", "六"
, "七", "八", "九"]; var chnUnitSection = ["", "萬", "億", "萬億", "億億"]; var chnUnitChar = ["", "十", "百", "千"]; function SectionToChinese(section) { var strIns = '', chnStr = ''; var unitPos = 0; var zero = true; while (section > 0) { var v = section % 10; if (v === 0
) { if (!zero) { zero = true; chnStr = chnNumChar[v] + chnStr; } } else { zero = false; strIns = chnNumChar[v]; strIns += chnUnitChar[unitPos]; chnStr = strIns + chnStr; } unitPos++; section = Math
.floor(section / 10); } return chnStr; } },
秒轉為小時分鐘過濾器
function toHHMMSS (sec, type, h_slug, m_slug, s_slug) {
    // 計算
    var sec_num = parseInt(sec, 10);
    var hours   = Math.floor( sec_num / 3600 );
    var minutes = Math.floor(( sec_num - ( hours * 3600 )) / 60 );
    var seconds = sec_num - ( hours * 3600 ) - ( minutes * 60 );

    // 低階格式化
    if (hours   < 10) { hours   = '0' + hours; }
    if (minutes < 10) { minutes = '0' + minutes; }
    if (seconds < 10) { seconds = '0' + seconds; }

    // 顯示規則
    var hour_display, minute_display, second_display;
    if (type) {
      hour_display = type.indexOf("H") > -1 && hours > 0 ? true : false;
      minute_display = type.indexOf("M") > -1 ? true : false;
      second_display = type.indexOf("S") > -1 ? true : false;
    } else {
      hour_display = minute_display = second_display = true;
    }

    // 自定義格式化
    var hour_slug = h_slug != undefined ? h_slug : ':';
    var minute_slug = m_slug != undefined ? m_slug : ':';
    var second_slug = s_slug != undefined ? s_slug : '';

    var time = ( hour_display ? hours + hour_slug : '' ) + ( minute_display ? minutes + minute_slug : '' ) + ( second_display ? seconds + second_slug : '' );
    return time;
  };