解决全网90%以上的日期格式转换、日期序列等骚操作问题
生活随笔
收集整理的這篇文章主要介紹了
解决全网90%以上的日期格式转换、日期序列等骚操作问题
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
function getYearMonthList(startDate, endDate) {//返回月份的數組 如 ['2021/07','2021/08']var arr = [];var s = new Date(startDate).toLocaleString("zh-Hans-CN", {year: "numeric", month: "2-digit", day: "2-digit"}).split("/");var e = new Date(endDate).toLocaleString("zh-Hans-CN", {year: "numeric", month: "2-digit", day: "2-digit"}).split("/");var min = new Date();var max = new Date();min.setFullYear(s[0], s[1] * 1 - 1, 1);//開始日期max.setFullYear(e[0], e[1] * 1 - 1, 1);//結束日期var curr = min;while (curr <= max) {var month = curr.getMonth();arr.push(curr.getFullYear() + "/" + (month + 1).toString().padStart(2, "0"));curr.setMonth(month + 1);}return arr;
}console.log(getYearMonthList(new Date(2020, 1, 1), new Date(2021, 1, 1)));
//["2020/02", "2020/03", "2020/04", "2020/05", "2020/06", "2020/07", "2020/08", "2020/09", "2020/10", "2020/11", "2020/12", "2021/01", "2021/02"]
function getYearMonthDayList(startDate, endDate) { //返回 日期的數組 如 ['2021/07/10','2021/07/11']var arr = [];var s = new Date(startDate).toLocaleString("zh-Hans-CN", {year: "numeric", month: "2-digit", day: "2-digit"}).split("/");var e = new Date(endDate).toLocaleString("zh-Hans-CN", {year: "numeric", month: "2-digit", day: "2-digit"}).split("/");var min = new Date();var max = new Date();min.setUTCFullYear(s[0], s[1] - 1, s[2]);max.setUTCFullYear(e[0], e[1] - 1, e[2]);var unixDb = min.getTime() - 24 * 60 * 60 * 1000;var unixDe = max.getTime() - 24 * 60 * 60 * 1000;for (var date = unixDb; date <= unixDe; date += 24 * 60 * 60 * 1000) {arr.push(new Date(date).toLocaleString("zh-Hans-CN", {year: "numeric", month: "2-digit", day: "2-digit"}));}return arr;
}console.log(getYearMonthDayList(new Date(2021, 7, 1), new Date(2021, 7, 11)));
//["2021/08/01", "2021/08/02", "2021/08/03", "2021/08/04", "2021/08/05", "2021/08/06", "2021/08/07", "2021/08/08", "2021/08/09", "2021/08/10", "2021/08/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, "-");// 當前日期轉換為: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, '-');},
總結
以上是生活随笔為你收集整理的解决全网90%以上的日期格式转换、日期序列等骚操作问题的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【全网最精简写法】ES6获取浏览器url
- 下一篇: 如何优雅地保留两位有效数字,又规避末尾出