likes
comments
collection
share

JS日期格式化;获取近7天、近半年、近一年日期(React、React Native)

作者站长头像
站长
· 阅读数 14

文档:JS日期对象

Date.prototype.Format = function (fmt) {
    let o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "H+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substring(4 - RegExp.$1.length));
    for (let k in o) {
        if (new RegExp("(" + k + ")").test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substring(("" + o[k]).length)));
        }
    }
    return fmt;
}

/**
 * @description: 日期格式转换
 * @param  {*}
 * @return {*}
 * @param {*} date new Date()参数:
 * new Date();无
 * new Date(value);Unix时间戳:1652054400000
 * new Date(dateString);时间戳字符串:'2020-05-09'
 * new Date(year, monthIndex [, day [, hours [, minutes [, seconds [, milliseconds]]]]]);分别提供日期与时间的每一个成员
 * @param {*} type 日期格式(英文按示例用,区分字母大小写) e.g "yyyy年MM月dd日 HH:mm:ss"
 */
export const getFormatDate = (date, type) => {
    let curDate = date || new Date()
    let newDate = new Date(curDate).Format(type)
    return newDate
}

/**
 * @description: 获取n年前指定日期
 * @param {*} n
 * @return {*} Unix Time Stamp e.g: 1652054400000
 */
export const getYearAgoDate = (n = 0) => {
    let curDate = new Date()
    curDate.setFullYear(curDate.getFullYear() - n)
    const ts = + curDate
    return ts
}

/**
 * @description: 获取n月前指定日期
 * @param {*} n
 * @return {*} Unix Time Stamp e.g: 1652054400000
 */
export const getMonthAgoDate = (n = 0) => {
    let curDate = new Date()
    curDate.setMonth(curDate.getMonth() - n)
    const ts = + curDate
    return ts
}

/**
 * @description: 获取n天前指定日期
 * @param {*} n
 * @return {*} Unix Time Stamp e.g: 1652054400000
 */
export const getDayAgoDate = (n = 0) => {
    let curDate = new Date();
    let newDate = new Date(curDate - 1000 * 60 * 60 * 24 * n);
    const ts = + newDate
    return ts
}