JS 对时间日期的转换与操作
admin
2024-04-14 13:44:38
0

JS 时间格式转换

this.timeFormatConvert(new Date()) // 2022-11-26 21:37:29

/** 时间格式转换* @param e 要转换的日期(如:Sat Nov 26 2022 21:37:29 GMT+0800 (中国标准时间))* @returns {string} 转换结果(如:2022-11-26 21:37:29)*/
timeFormatConvert(e) {const Y = e.getFullYear(); // 年const M = this.prefixZero(e.getMonth() + 1); // 月const D = this.prefixZero(e.getDate()); // 日const H = this.prefixZero(e.getHours()); // 时const Mi = this.prefixZero(e.getMinutes()); // 分const S = this.prefixZero(e.getSeconds()); // 秒return Y + "-" + M + "-" + D + " " + H + ":" + Mi + ":" + S;
},
prefixZero(num = 0, n = 2) {// 数字位数不够,数字前面补零return (Array(n).join("0") + num).slice(-n);
},

JS 获取当前年月日时分秒

this.getCurrTime("noGap") // 20221129154229

this.getCurrTime() // 2022-11-29 15:44:20

/** 获取当前年月日时分秒* @param e 默认.年月日时分秒 date.年月日 dateTime.年月日时分 noGap.无分隔符的年月日时分秒* @returns {string}*/
getCurrTime(e = "") {const curDate = new Date(),T = {Y: curDate.getFullYear().toString(), // 年M: this.prefixZero(curDate.getMonth() + 1), // 月D: this.prefixZero(curDate.getDate()), // 日H: this.prefixZero(curDate.getHours()), // 时Mi: this.prefixZero(curDate.getMinutes()), // 分S: this.prefixZero(curDate.getSeconds()), // 秒},tDate = T.Y + "-" + T.M + "-" + T.D; // 年月日let result = tDate + " " + T.H + ":" + T.Mi + ":" + T.S; // 年月日时分秒if (e === "date") result = tDate; // 年月日if (e === "dateTime") result = tDate + " " + T.H + ":" + T.Mi; // 年月日时分if (e === "noGap") result = T.Y + T.M + T.D + T.H + T.Mi + T.S; // 无分隔符return result;
},
prefixZero(num = 0, n = 2) {// 数字位数不够,数字前面补零return (Array(n).join("0") + num).slice(-n);
},

JS 获取n天前或n天后的日期

当前日期:2022-11-27

7天后的日期:this.getAgoLaterDate(7) // 2022-12-04

7天前的日期:this.getAgoLaterDate(-7) // 2022-11-20

/** 获取n天前或n天后的日期(默认当天)* @param n 需要的天数(+n之后的日期,-n之前的日期)* @returns {string} 默认返回当前日期*/
getAgoLaterDate(n = 0) {const curTime = new Date(),D1 = curTime.getDate(),date = new Date(curTime);date.setDate(D1 + n);const Y2 = date.getFullYear(),M2 = this.prefixZero(date.getMonth() + 1),D2 = this.prefixZero(date.getDate());return Y2 + "-" + M2 + "-" + D2;
},
prefixZero(num = 0, n = 2) {// 数字位数不够,数字前面补零return (Array(n).join("0") + num).slice(-n);
},

JS 获取指定日期的周一和周日

this.getSpecifyMonSun() // {mon: '2022-11-21', sun: '2022-11-27'}

this.getSpecifyMonSun("2022/11/17") // {mon: '2022-11-14', sun: '2022-11-20'}

/** 获取指定日期的周一和周日(默认当前日期)* @param e 需要指定的日期(格式:yyyy-MM-dd 或 yyyy/MM/dd 或 yyyy.MM.dd)* @returns {{mon: string, sun: string}} 默认返回当前日期的周一和周末日期*/
getSpecifyMonSun(e = new Date()) {const that = this,now = new Date(e),nowTime = now.getTime(),day = now.getDay() || 7, // 周日时day修改为7,否则获取的是下周一到周日的日期oneDayTime = 24 * 60 * 60 * 1000, // 一天的毫秒(ms)数mondayTime = new Date(nowTime - (day - 1) * oneDayTime), //周一的日期sundayTime = new Date(nowTime + (7 - day) * oneDayTime); //周日的日期function dataFormat(d) {const Y = d.getFullYear(), // 年M = that.prefixZero(d.getMonth() + 1), // 月D = that.prefixZero(d.getDate()); // 日return Y + "-" + M + "-" + D;}return { mon: dataFormat(mondayTime), sun: dataFormat(sundayTime) };
},
prefixZero(num = 0, n = 2) {// 数字位数不够,数字前面补零return (Array(n).join("0") + num).slice(-n);
},

JS 获取指定日期的月初和月末

this.getSpecifyEarlyEndMonth() // {first: '2022-11-01', end: '2022-11-30'}

this.getSpecifyEarlyEndMonth("2022/09") // {first: '2022-09-01', end: '2022-09-30'}

/** 获取指定日期的月初和月末(默认当前月)* @param e 需要指定的日期(格式:yyyy-MM 或 yyyy/MM 或 yyyy.MM)* @returns {{end: string, first: string}} 默认返回当前月的月初和月末日期*/
getSpecifyEarlyEndMonth(e = new Date()) {const that = this,nowDate = new Date(e), // 当前日期year = nowDate.getFullYear(), // 指定年month = nowDate.getMonth() + 1, // 指定月oneDayTime = 24 * 60 * 60 * 1000, // 一天的毫秒(ms)数firstDay = new Date(year, month - 1), // 当月第一天的日期lastDay = new Date(new Date(year, month).valueOf() - oneDayTime); // 当月最后一天的日期function dataFormat(d) {const Y = d.getFullYear(), // 年M = that.prefixZero(d.getMonth() + 1), // 月D = that.prefixZero(d.getDate()); // 日return Y + "-" + M + "-" + D;}return { first: dataFormat(firstDay), end: dataFormat(lastDay) };
},
prefixZero(num = 0, n = 2) {// 数字位数不够,数字前面补零return (Array(n).join("0") + num).slice(-n);
},

JS 根据当前时间判断是早上、中午、下午

this.getCurTimeState() // 晚上好

/** 根据当前时间判断是早上、中午、下午* @returns {string} 返回当前时间段对应的状态*/
getCurTimeState() {const nowTime = new Date(), // 获取当前时间hour = nowTime.getHours(); // 获取当前小时let result = ""; // 设置默认文字// 判断当前时间段if (hour >= 0 && hour <= 10) {result = "早上好";} else if (hour > 10 && hour <= 14) {result = "中午好";} else if (hour > 14 && hour <= 18) {result = "下午好";} else if (hour > 18 && hour <= 24) {result = "晚上好";}return result; // 返回当前时间段对应的状态
},

JS 将年月日时分秒转化为刚刚,几分钟前,几小时前,几天前等

this.timeConvertReveal("2020-11-27 14:38:16") // 2年前

this.timeConvertReveal() // 刚刚

/** 将年月日时分秒转化为刚刚,几分钟前,几小时前,几天前等(默认刚刚)* @param e 需要转换的时间(格式:yyyy-MM-dd HH:mm:ss 或 yyyy/MM/dd HH:mm:ss 或 yyyy.MM.dd HH:mm:ss)* @returns {string} 默认返回刚刚*/
timeConvertReveal(e = new Date()) {const minute = 1000 * 60, // 分钟hour = minute * 60, // 小时day = hour * 24, // 天week = day * 7, // 周month = day * 30, // 月year = month * 12, // 年curTime = new Date().getTime(), // 当前时间的时间戳specifyTime = new Date(e), // 指定时间的时间戳mistiming = curTime - specifyTime, // 时间差yearDiffer = mistiming / year, // 年差monthDiffer = mistiming / month, // 月差weekDiffer = mistiming / week, // 周差dayDiffer = mistiming / day, // 天差hourDiffer = mistiming / hour, // 时差minuteDiffer = mistiming / minute; // 分钟差let result = "-";if (yearDiffer >= 1) result = toInt(yearDiffer) + "年前";else if (monthDiffer >= 1) result = toInt(monthDiffer) + "月前";else if (weekDiffer >= 1) result = toInt(weekDiffer) + "周前";else if (dayDiffer >= 1) result = toInt(dayDiffer) + "天前";else if (hourDiffer >= 1) result = toInt(hourDiffer) + "小时前";else if (minuteDiffer >= 1) result = toInt(minuteDiffer) + "分钟前";else result = "刚刚";function toInt(num) {return parseInt(num.toString());}return result;
},

JS 获得指定月份的天数

this.getMonthDays("2022-10") // 31

/** 获得指定月份的天数(默认当前月)* @param e 需要指定的日期(格式:yyyy-MM 或 yyyy/MM 或 yyyy.MM)* @returns {number} 默认返回当前月的天数*/
getMonthDays(e = new Date()) {const now = new Date(e), // 指定日期nowYear = now.getYear(), // 指定年份nowMonth = now.getMonth(), // 指定月份startDate = new Date(nowYear, nowMonth, 1), // 开始日期endDate = new Date(nowYear, nowMonth + 1, 1); // 结束日期return (endDate - startDate) / (1000 * 60 * 60 * 24);
},

JS 获取指定日期是周几

this.getCurrWeek("2022-11-24") // 周四

this.getCurrWeek() // 周二

/** 获取指定日期是周几* @param e 需要指定的日期(格式:yyyy-MM-dd 或 yyyy/MM/dd 或 yyyy.MM.dd)* @returns {string} 默认返回当前日期是周几*/
getCurrWeek(e = new Date()) {const day = new Date(e).getDay(),weeks = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];return weeks[day];
},

JS 计算两个时间的时间差

this.getTimeDiff("2022-11-28 19:30:24") // {text: '时间已超过30分钟', timeDiff: '0天21时28分40秒40毫秒', dateObj: {day: 0, hour: 21, min: 28, sec: 40, ms: 40}}

/** 计算两个时间的时间差(timeDiff返回格式为xx天xx时xx分xx秒xx毫秒)* @param startTime 开始时间(格式:yyyy-MM-dd HH:mm:ss 或 yyyy/MM/dd HH:mm:ss 或 yyyy.MM.dd HH:mm:ss [需小于结束时间])* @param endTime 结束时间(格式:yyyy-MM-dd HH:mm:ss 或 yyyy/MM/dd HH:mm:ss 或 yyyy.MM.dd HH:mm:ss [默认当前时间])* @returns {string|{timeDiff: string, text: string, dateObj: {sec: number, min: number, hour: number, ms: number, day: number}}}*/
getTimeDiff(startTime, endTime = new Date()) {if (!startTime) return "错误:开始时间为必填";const diffVal = new Date(endTime) - new Date(startTime); // 两个时间戳相差的毫秒数if (diffVal < 0) return "错误:开始时间大于结束时间";const day = Math.floor(diffVal / (24 * 3600 * 1000)), // 计算相差的天数remainDay = diffVal % (24 * 3600 * 1000), // 计算天数后剩余的毫秒数hour = Math.floor(remainDay / (3600 * 1000)), // 计算相差的小时数remainHour = remainDay % (3600 * 1000), // 计算小时数后剩余的毫秒数min = Math.floor(remainHour / (60 * 1000)), // 计算相差的分钟数remainMinute = remainHour % (60 * 1000), // 计算分钟数后剩余的毫秒数sec = Math.round(remainMinute / 1000), // 计算相差的秒数remainSeconds = remainMinute % (60 * 1000), // 计算秒数后剩余的毫秒数ms = Math.round(remainSeconds / 1000), // 计算相差的毫秒数time = day + "天" + hour + "时" + min + "分" + sec + "秒" + ms + "毫秒",obj = { day: day, hour: hour, min: min, sec: sec, ms: ms };let val = "时间未超过30分钟";if (min > 30 || hour > 1) val = "时间已超过30分钟";return { text: val, timeDiff: time, dateObj: obj };
},

JS 从日期字符串中截取出年、月、日、时、分、秒

this.captureTime() // {day: "29", hour: "17", minute: "40", month: "11", second: "06", year: "2022"}

this.captureTime("2020-12-11 14:54:48") // {day: "11", hour: "14", minute: "54", month: "12", second: "48", year: "2020"}

/** 从日期字符串中截取出年、月、日、时、分、秒* @param e 需要截取的日期(格式:yyyy-MM-dd HH:mm:ss 或 yyyy/MM/dd HH:mm:ss 或 yyyy.MM.dd HH:mm:ss [默认当前日期])* @returns {{month: *, hour: *, year: *, day: *, minute: *, second: *}} 默认返回当前日期*/
captureTime(e = null) {let time = e;if (!e) {const curDate = new Date(),T = {Y: curDate.getFullYear().toString(), // 年M: this.prefixZero(curDate.getMonth() + 1), // 月D: this.prefixZero(curDate.getDate()), // 日H: this.prefixZero(curDate.getHours()), // 时Mi: this.prefixZero(curDate.getMinutes()), // 分S: this.prefixZero(curDate.getSeconds()), // 秒};time = T.Y + "-" + T.M + "-" + T.D + " " + T.H + ":" + T.Mi + ":" + T.S;}const timeArr = time.replace(/[:. /]/g, "-").split("-"); // 将":. /"换为"-",再根据"-"分组return {year: timeArr[0], // 年month: timeArr[1], // 月day: timeArr[2], // 日hour: timeArr[3], // 时minute: timeArr[4], // 分second: timeArr[5], // 秒};
},
prefixZero(num = 0, n = 2) {// 数字位数不够,数字前面补零return (Array(n).join("0") + num).slice(-n);
},

相关内容

热门资讯

【MySQL】锁 锁 文章目录锁全局锁表级锁表锁元数据锁(MDL)意向锁AUTO-INC锁...
【内网安全】 隧道搭建穿透上线... 文章目录内网穿透-Ngrok-入门-上线1、服务端配置:2、客户端连接服务端ÿ...
GCN的几种模型复现笔记 引言 本篇笔记紧接上文,主要是上一篇看写了快2w字,再去接入代码感觉有点...
数据分页展示逻辑 import java.util.Arrays;import java.util.List;impo...
Redis为什么选择单线程?R... 目录专栏导读一、Redis版本迭代二、Redis4.0之前为什么一直采用单线程?三、R...
【已解决】ERROR: Cou... 正确指令: pip install pyyaml
关于测试,我发现了哪些新大陆 关于测试 平常也只是听说过一些关于测试的术语,但并没有使用过测试工具。偶然看到编程老师...
Lock 接口解读 前置知识点Synchronized synchronized 是 Java 中的关键字,...
Win7 专业版安装中文包、汉... 参考资料:http://www.metsky.com/archives/350.htm...
3 ROS1通讯编程提高(1) 3 ROS1通讯编程提高3.1 使用VS Code编译ROS13.1.1 VS Code的安装和配置...
大模型未来趋势 大模型是人工智能领域的重要发展趋势之一,未来有着广阔的应用前景和发展空间。以下是大模型未来的趋势和展...
python实战应用讲解-【n... 目录 如何在Python中计算残余的平方和 方法1:使用其Base公式 方法2:使用statsmod...
学习u-boot 需要了解的m... 一、常用函数 1. origin 函数 origin 函数的返回值就是变量来源。使用格式如下...
常用python爬虫库介绍与简... 通用 urllib -网络库(stdlib)。 requests -网络库。 grab – 网络库&...
药品批准文号查询|药融云-中国... 药品批文是国家食品药品监督管理局(NMPA)对药品的审评和批准的证明文件...
【2023-03-22】SRS... 【2023-03-22】SRS推流搭配FFmpeg实现目标检测 说明: 外侧测试使用SRS播放器测...
有限元三角形单元的等效节点力 文章目录前言一、重新复习一下有限元三角形单元的理论1、三角形单元的形函数(Nÿ...
初级算法-哈希表 主要记录算法和数据结构学习笔记,新的一年更上一层楼! 初级算法-哈希表...
进程间通信【Linux】 1. 进程间通信 1.1 什么是进程间通信 在 Linux 系统中,进程间通信...
【Docker】P3 Dock... Docker数据卷、宿主机与挂载数据卷的概念及作用挂载宿主机配置数据卷挂载操作示例一个容器挂载多个目...