JS格式化時間(支持小程序,兼容IOS)


const REGEX = /(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})/
/**
 * @function format time
 * @param val, format
 * @return {string}
 * @example
 *      <template>
 *          <div>
 *             <span>{{item.time | formatTime('yyyy/MM/dd hh:mm:ss')}}</span>
 *          </div>
 *       </template>
 *       import {formatTime} from '../../library/timeFormat'
 *       export default {
 *          filters: {formatTime}
 *       }
 */
export const formatTime = (val, format) => {
    if (val) {
        /**
         * @instructions 如果不是時間戳格式,且含有字符 '-' 則將 '-' 替換成 '/' && 刪除小數點及后面的數字
         * @reason 將 '-' 替換成 '/' && 刪除小數點及后面的數字 的原因是safari瀏覽器僅支持 '/' 隔開的時間格式
         */
        if (val.toString().indexOf('-') > 0) {
            val = val.replace(/T/g, ' ').replace(/\.[\d]{3}Z/, '').replace(/(-)/g, '/') // 將 '-' 替換成 '/'
            val = val.slice(0, val.indexOf('.')) // 刪除小數點及后面的數字
        }
        let date = new Date(val)
        date.setHours(date.getHours() + 8)
        const [whole, yy, MM, dd, hh, mm, ss] = date.toISOString().match(REGEX)
        const year = new Date().getFullYear()
        const month = new Date().getMonth() + 1
        const dates = new Date().getDate()
        if (format) {
            return format
                .replace('yyyy', yy)
                .replace('yy', yy.slice(2))
                .replace('MM', MM)
                .replace('dd', dd)
                .replace('hh', hh)
                .replace('mm', mm)
                .replace('ss', ss)
        } else {
            return [yy, MM, dd].join('-') + ' ' + [hh, mm, ss].join(':')
        }
    } else {
        return '--'
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM