pro----时间格式化封装

import conf from '../config';

const $ = {};

/**
 *
 * @param time
 * @returns {number}
 */

export const unify          = function (time) {
    time -= 0;
    if (('' + time).length === 10) {
        time *= 1000;
    }
    return time;
};
export const formatDiffTime = function (time) {
    let ago, curTime, diff, int;
    time    = unify(time);
    int     = parseInt;
    curTime = +new Date();
    diff    = curTime - time;
    ago     = '';
    if (1000 * 60 > diff) {
        ago = '刚刚';
    } else if (1000 * 60 <= diff && 1000 * 60 * 60 > diff) {
        ago = int(diff / (1000 * 60)) + '分钟前';
    } else if (1000 * 60 * 60 <= diff && 1000 * 60 * 60 * 24 > diff) {
        ago = int(diff / (1000 * 60 * 60)) + '小时前';
    } else if (1000 * 60 * 60 * 24 <= diff && 1000 * 60 * 60 * 24 * 30 > diff) {
        ago = int(diff / (1000 * 60 * 60 * 24)) + '天前';
    } else if (1000 * 60 * 60 * 24 * 30 <= diff && 1000 * 60 * 60 * 24 * 30 * 12 > diff) {
        ago = int(diff / (1000 * 60 * 60 * 24 * 30)) + '月前';
    } else {
        ago = int(diff / (1000 * 60 * 60 * 24 * 30 * 12)) + '年前';
    }
    return ago;
}

export const timeFormat       = (time, format = 'yyyy-MM-dd hh:mm:ss') => {

    const time_type = typeof time;
    const date      = time_type === 'object' ? time : time_type === 'number' ? new Date(time) : new Date();
    const o         = {
        'M+': date.getMonth() + 1, //月份
        'd+': date.getDate(), //日
        'h+': date.getHours(), //小时
        'm+': date.getMinutes(), //分
        's+': date.getSeconds(), //秒
        'q+': Math.floor((date.getMonth() + 3) / 3), //季度
        'S' : date.getMilliseconds(), //毫秒
    };
    if (/(y+)/.test(format))
        format = format.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
    for (let k in o)
        if (new RegExp('(' + k + ')').test(format))
            format = format.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)));
    return format;
};
/**
 * 调试信息
 * @param msg
 */

             export const log = (msg) => {
    if (process.env.NODE_ENV !== 'production') {
        console.log(msg)
    }
};

/**
 * 本地localStore存储
 * @param key
 * @param value
 * @returns {*}
 */
export const localStore = (key, value) => {
    if (!key) return false;
    return value ? (localStorage.setItem(key, JSON.stringify(value))) : JSON.parse(localStorage.getItem(key));
};

/**
 * 本地sessionStore存储
 * @param key
 * @param value
 * @returns {*}
 */
export const sessionStore = (key, value) => {
    if (!key) return false;
    return value ? (sessionStorage.setItem(key, JSON.stringify(value))) : JSON.parse(sessionStorage.getItem(key));
};

/**
 * 文件上传
 * @param files
 * @param host
 * @param param
 * @param options
 */

$.uploadFile = (files, host, param, options) => {
    // 添加图片数据
    const formdata = new FormData();

    Object.keys(param).forEach(key => {
        formdata.append(key, param[key])
    });
    files.forEach(file => {
        formdata.append('file', file)
    });
    // 定义 xhr
    const xhr = new XMLHttpRequest();
    xhr.open('POST', host);
    // 设置超时
    xhr.ontimeout          = (res) => {

        options.error && options.error(res);
    };
    // 返回数据
    xhr.onreadystatechange = () => {
        if (xhr.readyState === 4) {
            if (xhr.status === 200) {
                options.success && options.success('upload success');

            } else {
                options.error && options.error('upload error');

            }
        }
    };
    // 发送请求
    xhr.send(formdata)
};

/**
 * 获取上传签名
 * @returns {Promise<*>}
 */
export const upload_sign = async () => {
    let res = await ax.get('/oss');
    if (res.status === 200) {
        return res.data;
    }
}

export const upload_img = (para, name, count, callback) => {
    let time        = (new Date()).getTime();
    let uploadCount = 0,
        self        = this;
    weui.uploader('#' + name, {
        url     : para.host,
        compress: {
            width  : 1600,
            height : 1600,
            quality: .85,
        },
        onBeforeQueued(files) {
            // `this` 是轮询到的文件, `files` 是所有文件
            if (['image/jpg', 'image/jpeg', 'image/png', 'image/gif'].indexOf(this.type) < 0) {
                weui.alert('请上传图片');
                return false; // 阻止文件添加
            }
            if (this.size > 10 * 1024 * 1024) {
                weui.alert('请上传不超过10M的图片');
                return false;
            }
            if (files.length > count) {
                weui.alert('最多只能上传1张图片,请重新选择');
                return false;
            }
            if (uploadCount >= count) {
                weui.alert('一次最多只能上传1张图片');
                return false;
            }
            ++uploadCount;
            time = (new Date()).getTime()
            return true; // 阻止默认行为,不插入预览图的框架
        },
        onBeforeSend(data, headers) {
            weui.loading('上传中...');
            // 扩展上传参数
            data.success_action_status = 200;
            data.OSSAccessKeyId        = para['accessid'];
            data.Signature             = para['signature'];
            data.policy                = para['policy'];
            data.key                   = para['dir'] + this.id + time + '.jpg';

        },
        onError : async function (err) {
            if (this.xhr && this.xhr.status === 200) {
                let img = para['dir'] + this.id + time + '.jpg';

                callback(img);
                weui.loading().hide();

                return true;// 阻止默认行为,不使用默认的失败态
            } else {
                weui.loading().hide();
                weui.alert('上传失败,请重新选择上传哦~');
            }
        },
    });
}
// 遍历对象
export const objForEach = (obj, fn) => {
    let key, result;
    for (key in obj) {
        if (obj.hasOwnProperty(key)) {
            result = fn.call(obj, key, obj[key]);
            if (result === false) {
                break
            }
        }
    }
};

// 遍历类数组
export const arrForEach = (fakeArr, fn) => {
    let i, item, result;
    const length = fakeArr.length || 0;
    for (i = 0; i < length; i++) {
        item   = fakeArr[i];
        result = fn.call(fakeArr, item, i);
        if (result === false) {
            break

        }
    }
};

export const monoObject     = (obj) => {
    if (typeof obj !== 'object') {
        return obj;
    }
    let newObj = {};
    for (let key in obj) {
        newObj[key] = $.monoObject(obj[key]);
    }
    return newObj;
};
export const setTitle       = (title) => {
    document.title = title;
};
export const scrolltobottom = (callback, offset) => {
    if (!callback) {
        window.off('scroll');
        return;
    }
    offset = offset || 44;
    window.on('scroll', function () {
        if (document.scrollTop() + offset >= document.height() - window.height()) callback();
    });
};

export const oss = conf.oss.dev
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值