解决全网90%以上的日期格式转换、日期序列等骚操作问题

简介: 解决全网90%以上的日期格式转换、日期序列等骚操作问题


计算某日期到某日期相差天数

parseInt(Math.abs(new Date('1988-07-11') - new Date('2023-07-11')) / (1000*60*60*24))

计算某日期到某日期相差月份数

function getDiffMonths(startDate, endDate) {
    //startDate、endDate的格式可以为“yyyy/MM/dd”、“yyyy-MM-dd”、“yyyy年MM月dd日”或Date();
    //返回日期的数组 如 ['2021/07/10','2021/07/11']
    let sd = new Date(startDate), sy = sd.getFullYear(), sm = sd.getMonth() + 1, sms = sy * 12 + sm,ed = new Date(endDate), ey = ed.getFullYear(), em = ed.getMonth() + 1, ems = ey * 12 + em;
    return Math.abs(ems - sms);
}
console.log(getDiffMonths('1988-07-11','2023-07-11'))

//计算两个日期之间相差几个月
function getDisMonths(startDate, endDate) {
    startDate = new Date(startDate).toLocaleString("zh-Hans-CN", {year: "numeric", month: "2-digit", day: "2-digit"}).split("/");
    endDate = new Date(endDate).toLocaleString("zh-Hans-CN", {year: "numeric", month: "2-digit", day: "2-digit"}).split("/");
    var year1 = parseInt(startDate[0]),
        month1 = parseInt(startDate[1]),
        year2 = parseInt(endDate[0]),
        month2 = parseInt(endDate[1]),
        months = Math.abs(year2 - year1) * 12 + Math.abs(month2 - month1);
    return months;
}
console.log(getDisMonths(new Date(2020, 5), new Date(2021, 7)));//14
// 当前日期转换为:yyyy/MM/dd HH:mm:ss(24小时制)________________________
new Date().toLocaleString("zh-Hans-CN", {dateStyle: "short", timeStyle: "medium", hour12: false});
// 当前日期转换为:yyyy/MM/dd 上午/下午HH:mm:ss(12小时制)________________________
new Date().toLocaleString("zh-Hans-CN", {dateStyle: "short", timeStyle: "medium"});
// 当前日期转换为:yyyy-MM-dd HH:mm:ss(24小时制 双位数)年月日时分秒________________________
new Date().toLocaleString("zh-Hans-CN", {year: "numeric", month: "2-digit", day: "2-digit", hour12: false, hour: "2-digit", minute: "2-digit", second: "2-digit"}).replace(/\//g, "-");
// 当前日期转换为:yyyyMMddHHmmss(24小时制 双位数)年月日时分秒________________________
new Date().toLocaleString("zh-Hans-CN", { year: "numeric", month: "2-digit", day: "2-digit", hour12: false, hour: "2-digit", minute: "2-digit", second: "2-digit" }).replace(/[\/ :]/g, "");
// 当前日期转换为:yyyy-MM-dd________________________
new Date().toLocaleString("zh-Hans-CN", {year: "numeric", month: "2-digit", day: "2-digit"}).replace(/\//g, "-");
// 当前日期转换为:HH:mm:ss(24小时制 双位数)________________________
new Date().toLocaleString("zh-Hans-CN", {hour: "2-digit", minute: "2-digit", second: "2-digit", hour12: false});
// 当前日期转换为:HH:mm(24小时制 双位数)________________________
new Date().toLocaleString("zh-Hans-CN", {hour: "2-digit", minute: "2-digit", hour12: false});
// 当前日期转换为:公元yyyy年MM月dd日星期D HH:mm:ss(24小时制)________________________
new Date().toLocaleString("zh-Hans-CN", {era:'short',year: "numeric", month: "short", day: "numeric", weekday: "long", hour: "numeric", minute: "numeric", second: "numeric", hour12: false});
// 当前日期转换为:yyyy年MM月dd日星期D HH:mm:ss(24小时制)________________________
new Date().toLocaleString("zh-Hans-CN", {year: "numeric", month: "short", day: "numeric", weekday: "long", hour: "numeric", minute: "numeric", second: "numeric", hour12: false});
// 当前日期转换为:yyyy年MM月dd日周D HH:mm:ss(24小时制)________________________
new Date().toLocaleString("zh-Hans-CN", {year: "numeric", month: "short", day: "numeric", weekday: "short", hour: "numeric", minute: "numeric", second: "numeric", hour12: false});
// 当前日期转换为:yyyy年MM月dd日D HH:mm:ss(24小时制)________________________
new Date().toLocaleString("zh-Hans-CN", {year: "numeric", month: "short", day: "numeric", weekday: "narrow", hour: "numeric", minute: "numeric", second: "numeric", hour12: false});
// 当前日期转换为:yyyy年MM月dd日星期D HH:mm:ss(24小时制)________________________
new Date().toLocaleString("zh-Hans-CN", {year: "numeric", month: "short", day: "numeric", hour: "numeric", minute: "numeric", second: "numeric", hour12: false});
// 当前日期转换为:yyyy年MM月dd日星期D________________________
new Date().toLocaleString("zh-Hans-CN", {year: "numeric", month: "short", day: "numeric", weekday: "long"});
// 当前日期转换为:yyyy年MM月dd日周D________________________
new Date().toLocaleString("zh-Hans-CN", {year: "numeric", month: "short", day: "numeric", weekday: "short"});
// 当前日期转换为:yyyy年MM月dd日D________________________
new Date().toLocaleString("zh-Hans-CN", {year: "numeric", month: "short", day: "numeric", weekday: "narrow"});
// 当前日期转换为:yyyy年MM月dd日________________________
new Date().toLocaleString("zh-Hans-CN", {year: "numeric", month: "short", day: "numeric"});
//部分笨拙的方法________________________
var yearMonthDay = new Date().getFullYear() + ("0" + (new Date().getMonth() + 1)).slice(-2) + ("0" + new Date().getDate()).slice(-2);//yyyyMMdd
var year_Month_Day = new Date().getFullYear() + "-" + ("0" + (new Date().getMonth() + 1)).slice(-2) + "-" + ("0" + new Date().getDate()).slice(-2);//yyyy-MM-dd
//部分笨拙的方法(ES6)________________________
var yearMonthDay = new Date().getFullYear() + (new Date().getMonth() + 1).toString().padStart(2, 0) + (new Date().getDate()).toString().padStart(2, 0);//yyyyMMdd
var year_Month_Day = new Date().getFullYear() + "-" + (new Date().getMonth() + 1).toString().padStart(2, 0) + "-" + (new Date().getDate()).toString().padStart(2, 0);//yyyy-MM-dd
//当月第一天、当月最后一天年月日(yyyy-MM-dd)________________________
new Date(new Date().getFullYear(),new Date().getMonth(),1).toLocaleString("zh-Hans-CN", {year: "numeric", month: "2-digit", day: "2-digit"}).replace(/\//g, "-");
new Date(new Date().getFullYear(),new Date().getMonth()+1,0).toLocaleString("zh-Hans-CN", {year: "numeric", month: "2-digit", day: "2-digit"}).replace(/\//g, "-");
/**日期方法大合集*/
var date = {
        //新方法(时:分:秒)
        HH_mm_ss(date = null) {
            return new Date(date).toLocaleString("zh-Hans-CN", { hour: "2-digit", minute: "2-digit", second: "2-digit", hour12: false });
        },
        //新方法(年-月-日)
        yyyy_MM_dd(date = null) {
            return new Date(date).toLocaleString("zh-Hans-CN", { year: "numeric", month: "2-digit", day: "2-digit" }).replace(/\//g, "-");
        },
        //新方法(年-月-日 时:分:秒)
        yyyy_MM_dd_HH_mm_ss(date = null) {
            return new Date(date).toLocaleString("zh-Hans-CN", { year: "numeric", month: "2-digit", day: "2-digit", hour12: false, hour: "2-digit", minute: "2-digit", second: "2-digit" }).replace(/\//g, "-");
        },
    yearMonthDay: function () {
        return new Date().getFullYear() + ("0" + (new Date().getMonth() + 1)).slice(-2) + ("0" + new Date().getDate()).slice(-2);
    }, year_Month_Day: function () {
        return new Date().getFullYear() + "-" + ("0" + (new Date().getMonth() + 1)).slice(-2) + "-" + ("0" + new Date().getDate()).slice(-2);
    }, yMd: function (dt, split) {
        dt || (dt = new Date());
        split || (split = "-");
        return dt.getFullYear() + split + ("0" + (dt.getMonth() + 1)).slice(-2) + split + ("0" + dt.getDate()).slice(-2);
    },
    /**判断是否逾期*/
    over: function (endDate, isEqual) {
        var d1 = new Date().getTime(), d2 = new Date(endDate).getTime();
        return isEqual ? d1 >= d2 : d1 > d2;
    },
    /**比较日期大小,前一个日期大于(isEqual=true时 比较大于等于)后一个日期时返回true*/
    compare: function (d1, d2, isEqual) {
        d1 = new Date(d1).getTime(), d2 = new Date(d2).getTime();
        return isEqual ? d1 >= d2 : d1 > d2;
    },
    /**获取指定日期之前/之后的某天*/
    pointDate: function (dt, n) {
        if (!n) return dt;
        var s = "/";
        if (dt.indexOf("-") > -1) {
            s = "-", dt = dt.replace(/-/g, "/");
        } else if (dt.indexOf(".") > -1) {
            s = ".", dt = dt.replace(/\./g, "/");
        }
        var d = new Date(dt), lw = new Date(Number(d) + 1000 * 60 * 60 * 24 * Math.floor(n)), /*n天数*/ ly = lw.getFullYear(), lm = lw.getMonth() + 1, ld = lw.getDate(), sd = ly + s + (lm < 10 ? "0" + lm : lm) + s + (ld < 10 ? "0" + ld : ld);
        return sd;
    },
    /**获得当前日期之前之后任意天的日期*/
    anyDate: function (n) {
        var dt = new Date();
        dt.setDate(dt.getDate() + n);
        return this.yMd(dt);
    },
    /**获得当前日期之前之后任意天的日期+时间*/
    anyDateTime: function (n) {
        var dt = new Date();
        dt.setDate(dt.getDate() + n);
        return formatDateTime(dt);
    },
    /**获得任意天的日期时间戳:n为负数就是过去的天数,正数则为未来的天数*/
    anyDateTimeStamp: function (n) {
        return new Date(date.anyDate(n) + " 00:00:00").getTime();
    },
    /**获得本月的开始日期、结束日期*/
    monthStartOrEndDate: function (isStart) {
        var now = new Date(), m = now.getMonth(), y = now.getFullYear(), msd = new Date(y, m, Boolean(isStart) ? 1 : new Date(y, m + 1, 0).getDate());
        return date.yMd(msd);
    },
    /**获得本周的开始日期、结束日期*/
    weekStartOrEndDate: function (isStart) {
        var now = new Date(), d = now.getDay(), nd = now.getDate(), m = now.getMonth(), y = now.getFullYear(), wsd = new Date(y, m, nd + (Boolean(isStart) ? -d : 6 - d));
        return date.yMd(wsd);
    },
    /**计算指定日期加上多少天、加多少月、加多少年的日期*/
    add: function (type, number, date) {
        var d = date ? (date instanceof Date ? date : new Date(date)) : new Date();
        switch (type) {
            case "y":
                d.setFullYear(d.getFullYear() + number);
                return d;
            case "q":
                d.setMonth(d.getMonth() + number * 3);
                return d;
            case "m":
                d.setMonth(d.getMonth() + number);
                return d;
            case "w":
                d.setDate(d.getDate() + number * 7);
                return d;
            case "d":
                d.setDate(d.getDate() + number);
                return d;
            case "h":
                d.setHours(d.getHours() + number);
                return d;
            case "m":
                d.setMinutes(d.getMinutes() + number);
                return d;
            case "s":
                d.setSeconds(d.getSeconds() + number);
                return d;
            default:
                d.setDate(d.getDate() + number);
                return d;
        }
        /*/!* 加2天.*!/ alert(date.add("d ", 2).toLocaleString()) /!* 加2月.*!/ alert(date.add("m ", 2).toLocaleString()) /!* 加2年*!/ alert(date.add("y ", 2).toLocaleString());*/
    },
    format: function (date, fmt) {
        date = date instanceof Date ? date : new Date(date);
        var o = {
            "M+": date.getMonth() + 1,
            "d+": date.getDate(),
            "h+": date.getHours() % 12 == 0 ? 12 : date.getHours() % 12,
            "H+": date.getHours(),
            "m+": date.getMinutes(),
            "s+": date.getSeconds(),
            "q+": Math.floor((date.getMonth() + 3) / 3),
            "S": date.getMilliseconds()
        };
        if (/(y+)/.test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
        }
        if (/(E+)/.test(fmt)) {
            fmt = fmt.replace(RegExp.$1, ((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? "星期" : "周") : "") + "日一二三四五六".charAt(date.getDay()));
        }
        for (var k in o) {
            if (new RegExp("(" + k + ")").test(fmt)) {
                fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
            }
        }
        return fmt;
    },
    /**格式化日期:yyyy-MM-dd HH:mm:ss */
    formatDate: function (timeStamp) {
        return date.format(timeStamp ? (timeStamp instanceof Date ? timeStamp : new Date(timeStamp)) : new Date(), "yyyy-MM-dd");
    },
    /**格式化日期:yyyy-MM-dd HH:mm:ss */
    formatDateTime: function (timeStamp) {
        return date.format(timeStamp ? (timeStamp instanceof Date ? timeStamp : new Date(timeStamp)) : new Date(), "yyyy-MM-dd HH:mm:ss");
    },
    /**格式化日期:yyyy年MM月dd日 HH:mm:ss */
    formatToyyyyMMddHHmmssEE: function (timeStamp) {
        return date.format(timeStamp ? (timeStamp instanceof Date ? timeStamp : new Date(timeStamp)) : new Date(), "yyyy年MM月dd日 HH:mm:ss EE");
    }, getDay: function () {
        return "星期" + "日一二三四五六".charAt(new Date().getDay());
    },
    /**转换Date为24小时计时时间格式*/
    to24hours: function (date) {
        var now = date ? (date instanceof Date ? date : new Date(date)) : new Date(), now = now.toLocaleTimeString("zh-Hans-CN", {hour12: false}), now = now.substr(0, now.lastIndexOf(":"));
        return now;
    },
    /**将秒数量转换为时分秒字符串*/
    toHourMinuteSecond: function (second, data) {
        var t = "",
            s = Math.round(second),
            d = data.isDoubleDigits,//显示双位数
            hz = data.hideZero,//隐藏为0的时间单位
            hh = data.hideHour,//隐藏小时
            hm = data.hideMinute,//隐藏分钟
            hs = data.hideSecond;//隐藏秒钟
        if (s > 0) {
            var hour = Math.floor(s / 3600), min = Math.floor(s / 60) % 60, sec = s % 60;
            hh || (hz && !hour) || (d && hour < 10 && (t += "0"), t += hour + "时");
            hm || (hz && !min) || (d && min < 10 && (t += "0"), t += min + "分");
            hs || (hz && !sec) || (d && sec < 10 && (t += "0"), t += sec + "秒");
        }
        return t;
        //测试用例
        /*alert(toHourMinuteSecond(3661,{
            // isDoubleDigits:true,
            hideZero:true,
            // hideHour:true,
            // hideMinute:true,
            // hideSecond:true,
        }));*/
    },
    /**获取最近几个月的年月份*/
    getRecentSeveralMonth: function (n) {
        var date = new Date();
        var nearMonth = [];
        for (var i = 1; i <= n; i++) {
            date.setMonth(date.getMonth() - 1);
            nearMonth.unshift(date.getFullYear() + "/" + (date.getMonth() + 1));
        }
        return nearMonth;
    },
    /**把时间转换为分钟数*/
    hourMinuteToMinute: function (timeString) {
        timeString = timeString.replace(/:/g, ":").replace(/\ |\ /g, "").replace(/::/g, ":").split(":");
        return parseInt(timeString[0] * 60) + parseInt(timeString[1]);
    },
    /**显示几分钟前刚刚发布文章*/
    timeAgo: function (timeStamp) {
        var minute = 1000 * 60, hour = minute * 60, day = hour * 24, week = day * 7, month = day * 30, now = new Date().getTime(), diffValue = now - timeStamp;
        var minC = diffValue / minute, hourC = diffValue / hour, dayC = diffValue / day, weekC = diffValue / week, monthC = diffValue / month, res;
        if (monthC > 3 && monthC < 12) {
            res = "半年前";
        } else if (monthC >= 1 && monthC <= 3) {
            res = parseInt(monthC) + "月前";
        } else if (weekC >= 1 && weekC < 4) {
            res = parseInt(weekC) + "周前";
        } else if (dayC >= 1 && dayC < 7) {
            res = parseInt(dayC) + "天前";
        } else if (hourC >= 1 && hourC < 24) {
            res = parseInt(hourC) + "小时前";
        } else if (minC >= 1 && minC < 60) {
            res = parseInt(minC) + "分钟前";
        } else if (diffValue >= 0 && diffValue <= minute) {
            res = "刚刚";
        } else {
            res = this.formatDateTime(timeStamp);
        }
        return res;
    }, between: function (startDate, endDate) {
        startDate = startDate instanceof Date ? startDate : new Date(startDate);
        endDate = endDate instanceof Date ? endDate : new Date(endDate);
        var today = new Date().getTime(), startDate = new Date(startDate).getTime(), endDate = new Date(endDate).getTime();
        return startDate < today && today < endDate;
    },
    /**计算两个日期相差天数*/
    getDayBetween: function (startDate, endDate) {
        return Math.floor(this.getMillisecondBetween(startDate, endDate)/ 86400000);
    },
    /**计算两个日期相差毫秒数*/
    getMillisecondBetween: function (startDate, endDate) {
        startDate = startDate instanceof Date ? startDate : new Date(startDate);
        endDate = endDate instanceof Date ? endDate : new Date(endDate);
        return Math.abs(Date.parse(endDate) - Date.parse(startDate));
    }
};
//获取周一的日期
getMonday() {
        var day = new Date().getDay(); //获取时间的星期数
        var time = new Date().setDate(new Date().getDate() - (day ? day - 1 : 6)); //获取minus天前的日期
        return new Date(time).toLocaleString("zh-Hans-CN", {year: "numeric", month: "2-digit", day: "2-digit"}) + " 00:00:00";
    },
//获取周五的日期
getFriday() {
        var day = new Date().getDay(); //获取时间的星期数
        var time = new Date().setDate(new Date().getDate() + (day ? 5 - day : -2)); //获取minus天前的日期
        return new Date(time).toLocaleString("zh-Hans-CN", {year: "numeric", month: "2-digit", day: "2-digit"}) + " 00:00:00";
    },
//获取周日的日期
getSunday(index) {
        var day = new Date().getDay(); //获取时间的星期数
        var time = new Date().setDate(new Date().getDate() + (index * 7) + (day ? 7 - day : 0)); //获取minus天前的日期
        return new Date(time).toLocaleString("zh-Hans-CN", {
          year: "numeric",
          month: "2-digit",
          day: "2-digit"
        }).replace(/\//g, '-');
    },

【年月日】、【年月】日期序列前往此处↓

image.png


相关文章
|
API
Angular 2.x折腾记 :(3)初步了解服务及使用
不探究高深理论,只探究实际使用,有更好的写法或者经验请指出; 有些暂时没涉及到的知识我可能会顺着例子解释;
127 0
|
JavaScript 前端开发 API
Angular 自定义服务 notification
比如,我们这篇文章要讲到的 notification 的实现。
Angular 自定义服务 notification
|
JSON 测试技术 数据格式
Angular如何对包含了HTTP请求的服务类进行单元测试
Angular如何对包含了HTTP请求的服务类进行单元测试
177 0
Angular如何对包含了HTTP请求的服务类进行单元测试
使用TestBed测试具有依赖关系的Angular服务
使用TestBed测试具有依赖关系的Angular服务
197 0
使用TestBed测试具有依赖关系的Angular服务
|
测试技术
对具有外部依赖的Angular服务类(service class)进行单元测试的几种方式
对具有外部依赖的Angular服务类(service class)进行单元测试的几种方式
122 0
对具有外部依赖的Angular服务类(service class)进行单元测试的几种方式
|
测试技术
使用jasmine.createSpyObj具有依赖关系的Angular服务进行单元测试
使用jasmine.createSpyObj具有依赖关系的Angular服务进行单元测试
116 0
使用jasmine.createSpyObj具有依赖关系的Angular服务进行单元测试
|
测试技术
对Angular使用了HttpClient的服务进行单元测试
对Angular使用了HttpClient的服务进行单元测试
104 0
对Angular使用了HttpClient的服务进行单元测试
Angular应用里使用HTTP服务的一个具体例子
Angular应用里使用HTTP服务的一个具体例子
Angular应用里使用HTTP服务的一个具体例子
|
缓存 网络架构
关于 Angular 服务实例作用域的问题 - 使用组件限定服务提供者的作用域
关于 Angular 服务实例作用域的问题 - 使用组件限定服务提供者的作用域
99 0
关于 Angular 服务实例作用域的问题 - 使用组件限定服务提供者的作用域

热门文章

最新文章