关于前端:JS日期格式化获取近7天近半年近一年日期ReactReact-Native

6次阅读

共计 1556 个字符,预计需要花费 4 分钟才能阅读完成。

文档: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)
    const ts = + newDate
    return ts
}

/**
 * @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
}
正文完
 0