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

文档: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
}

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理