1. 时间的格式化
-
代码的实现
/** * 时间的格式化 * @param {*} fmt 时间格式 * @returns */ Date.prototype.Format = function (fmt = "yyyy-MM-dd hh:mm:ss") { const self = new Date(this); // const platform = uni.getSystemInfoSync().platform; // if(platform == 'ios' ){ // fmt = fmt.replace(/-/g, '/'); // } const o = { "M+": self.getMonth() + 1, //月份 "d+": self.getDate(), //日 "h+": self.getHours(), //小时 "m+": self.getMinutes(), //分 "s+": self.getSeconds(), //秒 "q+": Math.floor((self.getMonth() + 3) / 3), //季度 S: self.getMilliseconds(), //毫秒 }; if (/(y+)/.test(fmt)) { fmt = fmt.replace( RegExp.$1, (self.getFullYear() + "").substr(4 - RegExp.$1.length) ); } for (const 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.replace(/T/g, " "); }; -
方法的使用
console.log(new Date("2023-11-12 13:14:00").Format('yyyy-MM-dd hh:mm:ss')); //2023-11-12 13:14:00 console.log(new Date().Format('yyyy-MM-dd hh:mm:ss')); //2024-11-12 16:31:03 console.log(new Date().Format('MM-dd hh:mm:ss')); //11-12 16:31:03 console.log(new Date().Format('MM-dd')); //11-12 console.log(new Date().Format('hh:mm')); //16:31 console.log(new Date().Format('yyyy年MM月dd日 hh时mm分ss秒')); //2024年11月12日 16时34分03秒 console.log(new Date().Format('yyyy年MM月dd日')); //2024年11月12日 console.log(new Date().Format('MM月dd日 hh时mm分ss秒')); //11月12日 16时34分03秒 console.log(new Date().Format('hh时mm分')); //16时34分 console.log(new Date().Format('yyyy/MM/dd')); //2024/11/12
2. 某月第一天
-
代码的实现
/** * 某月第一天 * @param {*} fmt * @returns */ Date.prototype.MonthFirstDay = function (fmt = "yyyy-MM-dd") { var year = this.getFullYear(); var month = this.getMonth() + 1; if (month == 0) { month = 12; year = year - 1; } if (month < 10) { month = "0" + month; } let startDate = year + "-" + month + "-01 00:00:00"; return new Date(startDate.replace(/ /g, "T")).Format(fmt); }; -
方法的使用
console.log(new Date("2024-10-12 13:14:00").MonthFirstDay()); //2024-10-01 console.log(new Date().MonthFirstDay()); //2024-11-01
3. 某月最后一天
- 代码的实现
/** * 某月最后一天 * @param {*} fmt * @returns */ Date.prototype.MonthLastDay = function (fmt = "yyyy-MM-dd") { var year = this.getFullYear(); var month = this.getMonth() + 1; if (month == 0) { month = 12; year = year - 1; } if (month < 10) { month = "0" + month; } var myDate = new Date(year, month, 0); let endDate = year + "-" + month + "-" + myDate.getDate() + " 23:59:59"; return new Date(endDate.replace(/ /g, "T")).Format(fmt); }; - 方法的使用
console.log(new Date("2024-10-12 13:14:00").MonthLastDay()); //2024-10-31 console.log(new Date().MonthLastDay()); //2024-11-30
4. 某周开始时间
- 代码的实现
/** * 某周开始时间 * @param {*} fmt * @returns */ Date.prototype.StartDateOfWeek = function (fmt = "yyyy-MM-dd") { const day = this.getDay() || 7; const nowDay = this.getDate(); // 当前日 const nowMonth = this.getMonth(); // 当前月 const count = nowDay + 1 - day; const dateStr = new Date( this.getFullYear(), this.getMonth(), count ).Format('yyyy-MM-dd'); return dateStr; }; - 方法的使用
console.log(new Date("2024-10-12 13:14:00").StartDateOfWeek()); //2024-10-07 console.log(new Date().StartDateOfWeek()); //2024-11-11
5.某周结束时间
- 代码的实现
/** * 某周结束时间 * @param {*} fmt * @returns */ Date.prototype.EndDateOfWeek = function (fmt = "yyyy-MM-dd") { const day = this.getDay() || 7; const nowDay = this.getDate(); // 当前日 const count = nowDay + 7 - day; const dateStr = new Date( this.getFullYear(), this.getMonth(), count ).Format('yyyy-MM-dd'); return dateStr; }; - 方法的使用
console.log(new Date("2024-10-12 13:14:00").EndDateOfWeek()); //2024-10-13 console.log(new Date().EndDateOfWeek()); //2024-11-17
6.指定日期多少天前后的日期
- 代码的实现
/** * 指定日期多少天前后的日期 * @param {*} day -1一天前日期 1明天日期 * @returns 对应的事件格式 */ Date.prototype.AppointDateDay = function (day = 0) { const nowDay = this.getDate(); // 当前日 const nowMonth = this.getMonth(); // 当前月 return new Date(this.getFullYear(), nowMonth, nowDay + day).Format("yyyy-MM-dd"); }; - 方法的使用
console.log(new Date("2024-10-12 13:14:00").AppointDateDay(-1)); //2024-10-11 console.log(new Date("2024-10-12 13:14:00").AppointDateDay(1)); //2024-10-13 console.log(new Date().AppointDateDay(-1)); //2024-11-11 console.log(new Date().AppointDateDay(1)); //2024-11-13
7.获取当前日期周几
-
代码的实现
/** * 获取当前日期周几 * @param {*} text text = 周 | 星期 * @returns */ Date.prototype.getWeeK = function (text = "周") { const day = this.getDay(); const weeks = ["日", "一", "二", "三", "四", "五", "六"]; return `${text}${weeks[day]}`; }; -
方法的使用
console.log(new Date("2024-10-12 13:14:00").getWeeK('星期')); //周六 console.log(new Date().getWeeK()); //周二 console.log(new Date("2024-10-12 13:14:00").getWeeK('星期')); //星期六 console.log(new Date().getWeeK('星期')); //星期二
8.查询指定时间段的时间
- 代码的实现
/** * 查询指定时间段的时间 * @param {*} begin 开始时间 * @param {*} end 结束时间 * @returns */ const getDateAll = (begin = '2024-11-12',end = '2024-11-17') => { var arr = []; var ab = begin.split("-"); var ae = end.split("-"); var db = new Date(); db.setUTCFullYear(ab[0], ab[1] - 1, ab[2]); var de = new Date(); de.setUTCFullYear(ae[0], ae[1] - 1, ae[2]); var unixDb = db.getTime() - 24 * 60 * 60 * 1000; var unixDe = de.getTime() - 24 * 60 * 60 * 1000; for (var k = unixDb; k <= unixDe; ) { k = k + 24 * 60 * 60 * 1000; arr.push(new Date(parseInt(k)).Format("yyyy-MM-dd")); } return arr; }; - 方法的使用
console.log(getDateAll()); // ['2024-11-12','2024-11-13','2024-11-14','2024-11-15','2024-11-16','2024-11-17']
9.如果年是今年,则不显示年份
-
代码的实现
/** * 如果年是今年,则不显示年份 * @param {*} fmt * @returns */ Date.prototype.FormatCurrDate = function (fmt = "yyyy年MM月dd日 hh:mm") { const date = new Date(); if (date.getFullYear() === this.getFullYear()) { fmt = fmt.replace(/yyyy年/g, ""); fmt = fmt.replace(/yyyy-/g, ""); fmt = fmt.replace(/yyyy\//g, ""); fmt = fmt.replace(/yyyy\./g, ""); } return this.Format(fmt); }; -
方法的使用
console.log(new Date('2023-12-22 12:00:00').FormatCurrDate()); //2023年12月22日 12:00 console.log(new Date().FormatCurrDate()); // 11月12日 17:33
10.时间简化 转换为 刚刚 今天 昨天 之类
- 代码的实现
/** * 时间简化 转换为 刚刚 今天 昨天 之类 * @returns */ Date.prototype.Short = function () { const dateTimeStamp = this.getTime(); const minute = 1000 * 60; //把分,时,天,周,半个月,一个月用毫秒表示 const hour = minute * 60; const day = hour * 24; const week = day * 7; const month = day * 30; const now = new Date().getTime(); //获取当前时间毫秒 const diffValue = now - dateTimeStamp; //时间差 if (diffValue < 0) { return; } const minC = parseInt(diffValue / minute); //计算时间差的分,时,天,周,月 const hourC = parseInt(diffValue / hour); const dayC = parseInt(diffValue / day); const weekC = parseInt(diffValue / week); const monthC = parseInt(diffValue / month); let result; if (monthC >= 1 && monthC <= 3) { result = " " + monthC + "月前"; } else if (weekC >= 1 && weekC <= 3) { result = " " + weekC + "周前"; } else if (dayC >= 1 && dayC <= 6) { result = " " + dayC + "天前"; } else if (hourC >= 1 && hourC <= 23) { result = " " + hourC + "小时前"; } else if (minC >= 1 && minC <= 59) { result = " " + minC + "分钟前"; } else if (diffValue >= 0 && diffValue <= minute) { result = "刚刚"; } else { result = this.FormatCurrDate(); } return result; }; - 方法的使用
console.log(new Date('2023-12-22 12:00:00').Short()); //2023年12月22日 12:00 console.log(new Date('2024-11-12 17:30:00').Short()); //1分钟前 console.log(new Date('2024-11-11 17:25:00').Short()); //1天前 console.log(new Date('2024-11-11 17:25:00').Short()); //1天前 console.log(new Date('2024-10-12 14:30:00').Short()); //1月前
说明:上面十种方法的实现是在第一种方法的基础上实现的
11. 格式化时间戳
-
代码实现
/** *@description 格式化时间戳 * @param {String} format YYYY-MM-DD hh:mm:ss * @param {String} daytime 时间戳,单位为毫秒 * @returns 返回格式化后的时间字符串 */ function formatTime(daytime, format = "YYYY-MM-DD hh:mm:ss") { const date = new Date(daytime); const year = date.getFullYear(); const month = ("0" + (date.getMonth() + 1)).slice(-2); const day = ("0" + date.getDate()).slice(-2); const hours = ("0" + date.getHours()).slice(-2); const minutes = ("0" + date.getMinutes()).slice(-2); const seconds = ("0" + date.getSeconds()).slice(-2); const map = { YYYY: String(year), MM: month, DD: day, hh: hours, mm: minutes, ss: seconds, }; return format.replace(/YYYY|MM|DD|hh|mm|ss/g, (matched) => map[matched]); } -
方法的使用
let data = new Date(); console.log(formatTime(data)); //2024-01-22 16:02:40
12. 支持各自格式的时间转化
-
代码的实现
/** * 支持各自格式的时间转化 * @param {*} daytime 传入的时间 * @param {*} format 时间格式 * @returns 返回对应的时间格式 */ const formatTime =(daytime, format = "YYYY-MM-DD hh:mm:ss") =>{ const date = new Date(daytime); if (isNaN(date.getTime())) { throw new Error("Invalid date string"); } const year = date.getFullYear(); const month = String(date.getMonth() + 1).padStart(2, '0'); const day = String(date.getDate()).padStart(2, '0'); const hours = String(date.getHours()).padStart(2, '0'); const minutes = String(date.getMinutes()).padStart(2, '0'); const seconds = String(date.getSeconds()).padStart(2, '0'); const map = { 'YYYY': year, 'MM': month, 'DD': day, 'hh': hours, 'mm': minutes, 'ss': seconds, 'yyyy年': `${year}年`, 'mm月': `${month}月`, 'dd日': `${day}日`, 'mm分': `${minutes}分`, 'ss秒': `${seconds}秒`, }; const regex = new RegExp(`(${Object.keys(map).join('|')})`, 'g'); let formattedTime = format.replace(regex, (matched) => map[matched]); return formattedTime; } -
方法的使用
// const timestamp = new Date().getTime(); // const timestamp = new Date() const timestamp = '2024-10-07 14:30:00' console.log(formatTime(timestamp, "YYYY-MM-DD hh:mm:ss")); // 2024-10-07 14:30:00 console.log(formatTime(timestamp, "hh:mm:ss")); // 14:30:00 console.log(formatTime(timestamp, "hh:mm")); // 14:30 console.log(formatTime(timestamp, "yyyy年mm月dd日 hh时mm分ss秒")); // 2024年30月07日 14时30分22秒 console.log(formatTime(timestamp, "yyyy年mm月dd日 hh时mm分")); // 2024年30月07日 14时30分 console.log(formatTime(timestamp, "yyyy年mm月dd日")); // 2024年10月07日 console.log(formatTime(timestamp, "hh时mm分")); // 14时30分 console.log(formatTime(timestamp, "YYYY/MM/DD")); // 2024/10/07
13.比较两个时间的大小,只处理HH:MM格式
-
代码的实现
/** * 比较两个时间的大小,只处理HH:MM格式 * @param {*} startTime 开始时间 * @param {*} endTime 结束时间 * @returns */ export function compareTimes(startTime, endTime) { // 解析时间字符串为小时和分钟 const parseTime = time => { const parts = time.split(':').map(Number); if ( parts.length !== 2 || parts[0] < 0 || parts[0] > 23 || parts[1] < 0 || parts[1] > 59 ) { throw new Error('时间格式错误,应为 "HH:MM",且小时为0-23,分钟为0-59'); } return { hour: parts[0], minute: parts[1] }; }; const t1 = parseTime(startTime); const t2 = parseTime(endTime); // 比较小时 if (t1.hour > t2.hour) { return 1; // startTime > endTime } else if (t1.hour < t2.hour) { return -1; // startTime < endTime } else { // 小时相等,比较分钟 if (t1.minute > t2.minute) { return 1; // startTime > endTime } else if (t1.minute < t2.minute) { return -1; // startTime < endTime } else { return 0; // startTime == endTime } } } -
方法的使用
console.log(compareTimes('9:00', '12:00')); // -1