moment.js 封装时间格式化方法

moment.js官网  http://momentjs.cn/

下载包

npm install moment --save

引入及使用

import moment from 'moment';

//距离目前时间差
export const longAgo = (params) => {
    let time = moment(params).fromNow();
    if (time == 'a few seconds ago') {
        return '1分钟前'
    } else if (time.includes('minute')) {
        if (time.slice(0, 1) == 'a') {
            return `1分钟前`;
        }
        return `${parseInt(time)}分钟前`;
    } else if (time.includes('hour')) {
        if (time.slice(0, 1) == 'a') {
            return `1小时前`;
        }
        return `${parseInt(time)}小时前`;
    } else if (time.includes('day')) {
        if (time.slice(0, 1) == 'a') {
            return `1天前`;
        }
        return `${parseInt(time)}天前`;
    } else if (time.includes('months')) {
        if (time.slice(0, 1) == 'a') {
            return `1个月前`;
        }
        return `${parseInt(time)}个月前`;
    } else if (time.includes('year')) {
        if (time.slice(0, 1) == 'a') {
            return `1年前`;
        }
        return `${parseInt(time)}年前`;
    }
}

//导出指定格式时间
export const dateTime = (params) => {
    return moment(params).format("YYYY/MM/DD  HH:mm:ss");
}
//导出指定格式时间
export const dateYearMouth = (params) => {
    return moment(params).format("YYYY/MM");
}
//导出指定格式时间
export const dateMouthDay = (params) => {
    return moment(params).format("MM/DD");
}

//导出时间倒计时
export const autoEndTime = (params) => {
    let now = moment();
    let expiration = moment(params)
    const diff = expiration.diff(now);
    const diffDuration = moment.duration(diff);
    return `将在${diffDuration.days()}天${diffDuration.hours()}小时${diffDuration.minutes()}分钟${diffDuration.seconds()}秒后结束`
}

//导出发送消息时间
export const createMsgTime = (params) => {
    if (moment(params).format("YYYY/MM/DD") == moment().format("YYYY/MM/DD")) {
        return moment(params).format("HH:mm")
    } else if (moment(params).format("YYYY") == moment().format("YYYY")) {
        return moment(params).format("MM/DD HH:mm")
    } else {
        return moment(params).format("YYYY/MM/DD HH:mm")
    }
}



//检查时间是否以过期
export const isBefore = (time) => {
    return moment(time).isBefore(new Date())
}


//倒计时 
//定时器每秒调用一次
setInterval(() => {
      let start = moment(new Date());//获取开始时间
      let end = moment(new Date("2020/12/20"));//结束时间
      let diff = end.diff(start);//时间差
      let time = `${moment.duration(diff).hours()} - ${moment.duration(diff).minutes()} - ${moment.duration(diff).seconds()}`//格式化为需要的格式 这里是时分秒
      console.log(time)
    }, 1000)

上一篇:在window平台下,自己DIY编译OpenSSL,Libcurl ,来支持HTTPS传输协议


下一篇:openmeetings-install分析(六)——ImportInitvalues类分析(4)