时间范围['2024-04-17 14:36:27', '2024-04-24 14:36:27']
console.log(this.$getrecentdays()); 页面使用默认7天 也可以指定console.log(this.$getrecentdays(30));
['2024-04-17 14:36:27', '2024-04-24 14:36:27'] 默认值
function getdatestring (date, fmt = 'yyyy-mm-dd') { if (/(y+)/.test(fmt)) { fmt = fmt.replace( regexp.$1, (date.getfullyear() + '').substr(4 - regexp.$1.length) ) } let o = { 'm+': date.getmonth() + 1, 'd+': date.getdate(), 'h+': date.gethours(), 'm+': date.getminutes(), 's+': date.getseconds(), } for (let k in o) { if (new regexp(`(${k})`).test(fmt)) { let str = o[k] + '' fmt = fmt.replace( regexp.$1, regexp.$1.length === 1 ? str : padleftzero(str) ) } } return fmt } export function getrecentdays (duration = 7, fmt = 'yyyy-mm-dd hh:mm:ss') { let onedaylong = 24 * 60 * 60 * 1000 let nowtime = date.now() let pre7daytime = nowtime - duration * onedaylong let now = new date(nowtime) let pre7day = new date(pre7daytime) return [getdatestring(pre7day, fmt), getdatestring(now, fmt)] }
开始时间结束时间['2024-04-17 00:00:00', '2024-04-24 23:59:59']
console.log(this.$todaytimer(30)); 也是可以自定义范围呢
export function todaytimer (duration = 7, fmt = 'yyyy-mm-dd') { let onedaylong = 24 * 60 * 60 * 1000 let nowtime = date.now() let pre7daytime = nowtime - duration * onedaylong let now = new date(nowtime) let pre7day = new date(pre7daytime) return [ getdatestring(pre7day, fmt) + ' ' + '00:00:00', getdatestring(now, fmt) + ' ' + '23:59:59', ] }
今年的起始时间 和结束时间 ['2024-01-01 00:00:00', '2024-12-31 23:59:59']
export function todaytimer (duration = 7, fmt = 'yyyy-mm-dd') { let onedaylong = 24 * 60 * 60 * 1000 let nowtime = date.now() let pre7daytime = nowtime - duration * onedaylong let now = new date(nowtime) let pre7day = new date(pre7daytime) return [ getdatestring(pre7day, fmt) + ' ' + '00:00:00', getdatestring(now, fmt) + ' ' + '23:59:59', ] }
当月的开始结束时间 ['2024-04-01 00:00:00', '2024-04-30 23:59:59']
export function ofmonth () { const startofmonth = moment().startof('month').format('yyyy-mm-dd 00:00:00'); // 本月的起始时间 const endofmonth = moment().endof('month').format('yyyy-mm-dd 23:59:59'); // 本月的结束时间 return [startofmonth, endofmonth] }
最近几个月 ['2023-10-31 00:00:00', '2024-04-30 23:59:59']
最近几个月 ['2023-10-31 00:00:00', '2024-04-30 23:59:59']
console.log(this.$recentmonths('month',6));
export function recentmonths (type, val) { const now = moment(); if (type == 'day') { const startdate = now.clone().subtract(val - 1, 'days').startof('day'); const enddate = now.clone().endof('day').hours(23).minutes(59).seconds(59); const dayrange = [startdate.format('yyyy-mm-dd hh:mm:ss'), enddate.format('yyyy-mm-dd hh:mm:ss')]; return dayrange; } if (type == 'week') { const weeksago = now.clone().subtract(val - 1, 'weeks').startof('isoweek'); const thisweekend = now.clone().endof('week').hours(23).minutes(59).seconds(59); const recentweeksrange = [weeksago.format('yyyy-mm-dd hh:mm:ss'), thisweekend.format('yyyy-mm-dd hh:mm:ss')]; // console.log(recentweeksrange); return recentweeksrange; } if (type == 'month') { const sixmonthsago = now.clone().subtract(val, 'months').endof('month').startof('day'); const thismonthend = now.clone().endof('month').hours(23).minutes(59).seconds(59); const recentsixmonthsrange = [ sixmonthsago.format('yyyy-mm-dd hh:mm:ss'), thismonthend.format('yyyy-mm-dd hh:mm:ss') ] return recentsixmonthsrange } }
各种时间类型就不一一列了
下面是完整的js代码
import * as moment from 'moment'; moment.suppressdeprecationwarnings = true; // 封装的 一些关于时间的方法 function random (low, high) { if (arguments.length === 1) { high = low low = 0 } return math.floor(low + math.random() * (high - low)) } function randomone (arr) { return arr[random(arr.length)] } function getdatestring (date, fmt = 'yyyy-mm-dd') { if (/(y+)/.test(fmt)) { fmt = fmt.replace( regexp.$1, (date.getfullyear() + '').substr(4 - regexp.$1.length) ) } let o = { 'm+': date.getmonth() + 1, 'd+': date.getdate(), 'h+': date.gethours(), 'm+': date.getminutes(), 's+': date.getseconds(), } for (let k in o) { if (new regexp(`(${k})`).test(fmt)) { let str = o[k] + '' fmt = fmt.replace( regexp.$1, regexp.$1.length === 1 ? str : padleftzero(str) ) } } return fmt } function getdatestringch (date) { if (!(date instanceof date)) { return '' } let year = date.getfullyear() let month = date.getmonth() + 1 let day = date.getdate() let hour = date.gethours() return `${year}年${month}月${day}日 ${hour}时` } function getweekstartdateandenddaterange () { let onedaylong = 24 * 60 * 60 * 1000 let now = new date() let mondaytime = now.gettime() - (now.getday() - 1) * onedaylong let sundaytime = now.gettime() + (7 - now.getday()) * onedaylong let monday = new date(mondaytime) let sunday = new date(sundaytime) let weekrange = [getdatestring(monday), getdatestring(sunday)] return weekrange } // ['2024-04-17 14:36:27', '2024-04-24 14:36:27'] 默认值 // console.log(this.$getrecentdays()); 页面使用 export function getrecentdays (duration = 7, fmt = 'yyyy-mm-dd hh:mm:ss') { let onedaylong = 24 * 60 * 60 * 1000 let nowtime = date.now() let pre7daytime = nowtime - duration * onedaylong let now = new date(nowtime) let pre7day = new date(pre7daytime) return [getdatestring(pre7day, fmt), getdatestring(now, fmt)] } function getmonthstartdateanddaterange () { let onedaylong = 24 * 60 * 60 * 1000 let now = new date() let year = now.getfullyear() let monthstartdate = new date(year, now.getmonth(), 1) //当前月1号 let nextmonthstartdate = new date(year, now.getmonth() + 1, 1) //下个月1号 let days = (nextmonthstartdate.gettime() - monthstartdate.gettime()) / onedaylong //计算当前月份的天数 let monthenddate = new date(year, now.getmonth(), days) let monthrange = [getdatestring(monthstartdate), getdatestring(monthenddate)] return monthrange } function padleftzero (str) { return ('00' + str).substr(str.length) } function resetform (refname) { this.$refs[refname] && this.$refs[refname].resetfields() } export function debounce (func, wait, immediate) { let timeout, args, context, timestamp, result const later = function () { // 据上一次触发时间间隔 const last = +new date() - timestamp // 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait if (last < wait && last > 0) { timeout = settimeout(later, wait - last) } else { timeout = null // 如果设定为immediate===true,因为开始边界已经调用过了此处无需调用 if (!immediate) { result = func.apply(context, args) if (!timeout) context = args = null } } } return function (...args) { context = this timestamp = +new date() const callnow = immediate && !timeout // 如果延时不存在,重新设定延时 if (!timeout) timeout = settimeout(later, wait) if (callnow) { result = func.apply(context, args) context = args = null } return result } } // console.log(this.$randomuuid()); // 1713940662895.5952 数据数 function randomuuid () { return date.now() + math.random() + '' } const resettimer = (timer) => { if (timer) { cleartimeout(timer) timer = null } } // ['2024-04-17 00:00:00', '2024-04-24 23:59:59'] 开始时间结束时间 export function todaytimer (duration = 7, fmt = 'yyyy-mm-dd') { let onedaylong = 24 * 60 * 60 * 1000 let nowtime = date.now() let pre7daytime = nowtime - duration * onedaylong let now = new date(nowtime) let pre7day = new date(pre7daytime) return [ getdatestring(pre7day, fmt) + ' ' + '00:00:00', getdatestring(now, fmt) + ' ' + '23:59:59', ] } // 今年的起始时间 和结束时间 ['2024-01-01 00:00:00', '2024-12-31 23:59:59'] export function ofyear () { const startofyear = moment().startof('year').format('yyyy-mm-dd 00:00:00'); const endofyear = moment().endof('year').format('yyyy-mm-dd 23:59:59'); return [startofyear, endofyear] } // 这个月的开始结束时间 ['2024-04-01 00:00:00', '2024-04-30 23:59:59'] export function ofmonth () { const startofmonth = moment().startof('month').format('yyyy-mm-dd 00:00:00'); // 本月的起始时间 const endofmonth = moment().endof('month').format('yyyy-mm-dd 23:59:59'); // 本月的结束时间 return [startofmonth, endofmonth] } // 上传json;模板 export function fundownload (content, filename) { // 创建隐藏的可下载链接 const elelink = document.createelement('a') elelink.download = filename elelink.style.display = 'none' // 字符内容转变成blob地址 let blob = new blob([content]) elelink.href = url.createobjecturl(blob) // 触发点击 document.body.appendchild(elelink) elelink.click() // 然后移除 document.body.removechild(elelink) } // 对象转json字符串 export function objtojson (obj) { let newobj = {} for (let key in obj) { if (key === 'id') { newobj[key] = obj[key] continue } newobj[key] = json.stringify(obj[key]) } return newobj } // 打印 export function print (id) { var bdhtml = window.document.body.innerhtml var jubudata = document.getelementbyid(id).innerhtml window.document.body.innerhtml = jubudata var style = document.createelement('style'); style.innerhtml = ` @media print { @page { size: auto; margin: 5mm; } body { margin: 0; } .no-print { display: none; } .el-divider { border: 1px solid #dcdfe6; margin: 24px 0; } } `; document.head.appendchild(style); const table = document.queryselectorall(".el-table__header,.el-table__body,.el-table__footer"); for (let i = 0; i < table.length; i++) { const tableitem = table[i]; tableitem.style.width = '100%'; const child = tableitem.childnodes; for (let j = 0; j < child.length; j++) { const element = child[j]; if (element.localname == 'colgroup') { element.innerhtml = ''; } } } window.print() location.reload() document.head.removechild(style); window.document.body.innerhtml = bdhtml } // 打印图片 export function printcanvas (id, i) { var oldstr = document.body.innerhtml // 获取当前页面内容用以还原 var div_print = document.getelementbyid(id) // 获取要打印部分的内容 var cv = document.getelementsbytagname('canvas')[i] //获取canvas var resimg = document.getelementbyid(id) //获取包裹canvas的标签 // 将canvas转为图片 // var context = cv.getcontext("2d") var img = new image() var strdatauri = cv.todataurl('image/png') img.src = strdatauri // 图片加载完成之后 img.onload = function () { // 执行打印 console.log(img); settimeout(function () { resimg.innerhtml = `<img src="${strdatauri}">` // 用图片替代canvas var newstr = div_print.innerhtml document.body.innerhtml = newstr // 将页面内容改为修改后的内容 window.print() // 打印 window.location.reload() // 重新加载页面 document.body.innerhtml = oldstr // 将页面内容还原 }, 1000) } } // 下载echarts为图片 export function exportpic (chartinstance, name = 'charts') { let picinfo = chartinstance.getdataurl({ type: 'png', pixelratio: 2, //放大两倍下载,之后压缩到同等大小展示。解决生成图片在移动端模糊问题 backgroundcolor: '#fff' });//获取到的是一串base64信息 const elink = document.createelement('a'); elink.download = name + '.png'; elink.style.display = 'none'; elink.href = picinfo; document.body.appendchild(elink); elink.click(); url.revokeobjecturl(elink.href); // 释放url 对象 document.body.removechild(elink) } // 复制 export function copytext (row, column, cell, event) { // 双击复制 let save = function (e) { e.clipboarddata.setdata('text/plain', event.target.innertext); e.preventdefault(); //阻止默认行为 } document.addeventlistener('copy', save);//添加一个copy事件 document.execcommand("copy");//执行copy方法 this.$message({ message: '复制成功', type: 'success' })//提示 } // ['2024-04-23 14:39:48', '2024-04-24 14:39:48'] export function getdefaulttimerange (type = "real", val, fmt = 'yyyy-mm-dd hh:mm:ss') { let start = new date() if (type === 'real') { start.setdate(start.getdate() - (val ? val : 1)) } if (type === 'hour') { start.setdate(start.getdate() - (val ? val : 1)) } if (type === 'day') { start.setmonth(start.getmonth() - (val ? val : 1)) } if (type === 'week') { start.setmonth(start.getmonth() - (val ? val : 3)) } if (type === 'month') { start.setfullyear(start.getfullyear() - (val ? val : 1)) } if (type === 'quarter') { val = val || 3; // 如果val未提供,则默认为3 start.setfullyear(start.getfullyear() - math.floor(val / 4)); start.setmonth(start.getmonth() - (val % 4) * 3); } if (type === 'year') { start.setfullyear(start.getfullyear() - (val ? val : 10)) } return [getdatestring(start, fmt), getdatestring(new date(), fmt)] } // ['2024-04-24 00:00:00', '2024-04-24 23:59:59'] 一天结束或开始 export function getdefaultdayrange (type = "real", fmt = 'yyyy-mm-dd hh:mm:ss') { let start = new date() let end = new date() if (type === 'real') { start.setdate(start.getdate()) end.setdate(start.getdate()) } if (type === 'hour') { start.setdate(start.getdate()) end.setdate(start.getdate()) } if (type === 'day') { start.setdate(1) end.setmonth(end.getmonth() + 1) end.setdate(0) } if (type === 'month') { start.setdate(1) start.setmonth(0) end.setfullyear(end.getfullyear() + 1) end.setmonth(0) end.setdate(0) } return [getdatestring(start, fmt).split(' ')[0] + ' 00:00:00', getdatestring(end, fmt).split(' ')[0] + ' 23:59:59'] } // 最近几个月 ['2023-10-31 00:00:00', '2024-04-30 23:59:59'] // console.log(this.$recentmonths('month',6)); export function recentmonths (type, val) { const now = moment(); if (type == 'day') { const startdate = now.clone().subtract(val - 1, 'days').startof('day'); const enddate = now.clone().endof('day').hours(23).minutes(59).seconds(59); const dayrange = [startdate.format('yyyy-mm-dd hh:mm:ss'), enddate.format('yyyy-mm-dd hh:mm:ss')]; return dayrange; } if (type == 'week') { const weeksago = now.clone().subtract(val - 1, 'weeks').startof('isoweek'); const thisweekend = now.clone().endof('week').hours(23).minutes(59).seconds(59); const recentweeksrange = [weeksago.format('yyyy-mm-dd hh:mm:ss'), thisweekend.format('yyyy-mm-dd hh:mm:ss')]; // console.log(recentweeksrange); return recentweeksrange; } if (type == 'month') { const sixmonthsago = now.clone().subtract(val, 'months').endof('month').startof('day'); const thismonthend = now.clone().endof('month').hours(23).minutes(59).seconds(59); const recentsixmonthsrange = [ sixmonthsago.format('yyyy-mm-dd hh:mm:ss'), thismonthend.format('yyyy-mm-dd hh:mm:ss') ] return recentsixmonthsrange } } // 参数为秒 返回时间 // console.log(this.$timerangeformat(600)); 10分钟 export function timerangeformat (seconds) { const timeunits = [ { label: '天', value: math.floor(seconds / (24 * 3600)) }, { label: '小时', value: math.floor((seconds % (24 * 3600)) / 3600) }, { label: '分钟', value: math.floor((seconds % 3600) / 60) }, { label: '秒', value: math.floor(seconds % 60) } ] return timeunits.filter(v => v.value > 0).map(item => `${item.value}${item.label}`).join('').trim() } // {startdatetime: '2023-03-03 00:00:00', enddatetime: '2023-03-03 23:59:59'} // console.log(this.$timerange('day','2023-03-03')); export function timerange (type, val) { let startdatetime, enddatetime; switch (type) { case 'hour': startdatetime = moment(val).startof('hour'); enddatetime = moment(val).endof('hour'); break; case 'day': startdatetime = moment(val).startof('day'); enddatetime = moment(val).endof('day'); break; case 'week': let value = val.tostring() const weekyear = value.substring(0, 4) const weeknumber = value.substring(4, 6) startdatetime = moment().isoweekyear(parseint(weekyear)).isoweek(parseint(weeknumber)).startof('isoweek'); enddatetime = moment().isoweekyear(parseint(weekyear)).isoweek(parseint(weeknumber)).endof('isoweek'); break; case 'month': startdatetime = moment(val, "yyyy-mm").startof('month'); enddatetime = moment(val, "yyyy-mm").endof('month'); break; case 'quarter': let valseason = val.tostring() const year = valseason.substring(0, 4) const quarter = valseason.substring(4, 5) startdatetime = moment().quarter(quarter).year(year).startof('quarter'); enddatetime = moment().quarter(quarter).year(year).endof('quarter'); break; case 'year': startdatetime = moment(val, "yyyy").startof('year'); enddatetime = moment(val, "yyyy").endof('year'); break; default: return; } startdatetime = startdatetime.format("yyyy-mm-dd hh:mm:ss"); enddatetime = enddatetime.format("yyyy-mm-dd hh:mm:ss"); return { startdatetime, enddatetime }; } export function timeformatting (type, val) { if (type == 'hour') { let hour = moment().set({ hour: val, minute: 0, second: 0, millisecond: 0 }).format('yyyy-mm-dd hh'); return hour } else if (type == 'day') { let day = moment().date(val).format('yyyy-mm-dd'); return day } else if (type == 'month') { let month = moment(val, 'mm').format('yyyy-mm'); return month } } // console.log(this.$timeformattype('day', '2023123')); 2023-12-03 export function timeformattype (type, val) { if (type == 'hour') { let [year, month, date, hour] = string(val).split(/(\d{4})(\d{2})(\d{2})(\d{2})/).slice(1); // 创建moment对象并设置时间 let momentdate = moment().set({ year: parseint(year), month: parseint(month) - 1, date: parseint(date), hour: parseint(hour), minute: 0, second: 0, millisecond: 0 }); // 格式化时间 let hourval = momentdate.format('yyyy-mm-dd hh'); return hourval } else if (type == 'day') { let day = moment(val, 'yyyymmdd').format('yyyy-mm-dd'); return day } else if (type == 'month') { const month = moment(val, 'yyyymm').format('yyyy-mm'); return month } else if (type == 'year') { const year = moment(val, 'yyyy').format('yyyy'); return year } else if (type == 'week') { const weekyear = val.tostring().substring(0, 4); const weeknum = val.tostring().substring(4); const startdate = moment(`${weekyear}-01-01`).add((weeknum) * 7, 'days').startof('isoweek'); let week = startdate.format('yyyy-ww'); return week } else if (type == 'quarter') { const quarteryear = val.tostring().substring(0, 4); const quarternum = val.tostring().substring(4); // 计算季度的第一天日期 const startdate = moment(`${quarteryear}-01-01`).add((quarternum - 1) * 3, 'months').startof('month'); let quarter = startdate.format('yyyy-q'); return quarter } } // console.log(this.$tenmonthsago(24, 'month')); // ['2022-04', '2024-04'] export function tenmonthsago (val, type) { if (type == 'hour') { return hour } else if (type == 'day') { return day } else if (type == 'month') { const tenmonthsago = moment().subtract(val, 'months').format('yyyy-mm'); const currentmonth = moment().format('yyyy-mm'); const month = [tenmonthsago, currentmonth]; return month } } export function tenmonthshistory (val, type) { if (type == 'hour') { return hour } else if (type == 'day') { return day } else if (type == 'month') { const tenmonthsago = moment().subtract(val, 'months').format('yyyy-mm'); const currentmonth = moment().subtract(1, 'months').format('yyyy-mm'); const month = [tenmonthsago, currentmonth]; return month } } // 20240101 console.log(this.$timetypeformatting('day', '2024-01-01'),); export function timetypeformatting (type, value) { switch (type) { case 'hour': return value.substring(0, 13).replace(/[- :]/g, ""); break; case 'day': return value.replace(/[- :]/g, ""); break; case 'week': return (moment(value).isoweekyear() + ' ' + moment(value).isoweek()).replace(/[- :]/g, ""); break; case 'month': return value.replace(/[- :]/g, ""); break; case 'year': return value.replace(/[- :]/g, ""); break; default: ''; } } export function getbase64 (file) { return new promise(function (resolve, reject) { const reader = new filereader() let imgresult = '' reader.readasdataurl(file) reader.onload = function () { imgresult = reader.result } reader.onerror = function (error) { reject(error) } reader.onloadend = function () { resolve(imgresult) } }) } export function getempty (val) { if (val !== null && val !== false && val !== undefined && val !== nan && val !== '') { return val } else { return '-' } } export function getemptyunit (val, unit) { if (val !== null && val !== false && val !== undefined && val !== nan && val !== '' && val != '0.00' && val !== 0 && val && val !== 'nan') { return unit } else { return '' } } export function findobjectbyvalue (arr, val) { let result = []; function search (arr, parentobjects = []) { for (let i = 0; i < arr.length; i++) { if (arr[i].id === val) { // 找到匹配项,将当前对象和所有父级对象都添加到结果数组 result.push(...parentobjects, arr[i]); } if (arr[i].childs && arr[i].childs.length > 0) { // 递归搜索子对象,将当前对象添加到父级对象数组中 search(arr[i].childs, [...parentobjects, arr[i]]); } } } search(arr); return result; } export default { install (vue) { this.addglobalmethods(vue) }, addglobalmethods (vue) { vue.prototype.$random = random vue.prototype.$resetform = resetform vue.prototype.$randomone = randomone vue.prototype.$getdatestring = getdatestring vue.prototype.$getrecentdays = getrecentdays vue.prototype.$getweekstartdateandenddaterange = getweekstartdateandenddaterange vue.prototype.$getmonthstartdateanddaterange = getmonthstartdateanddaterange vue.prototype.$debounce = debounce vue.prototype.$getdatestringch = getdatestringch vue.prototype.$randomuuid = randomuuid vue.prototype.$resettimer = resettimer vue.prototype.$todaytimer = todaytimer vue.prototype.$fundownload = fundownload vue.prototype.$objtojson = objtojson vue.prototype.$print = print vue.prototype.$printcanvas = printcanvas vue.prototype.$exportpic = exportpic vue.prototype.$copytext = copytext vue.prototype.$getdefaulttimerange = getdefaulttimerange vue.prototype.$timerangeformat = timerangeformat vue.prototype.$timerange = timerange vue.prototype.$ofyear = ofyear vue.prototype.$ofmonth = ofmonth vue.prototype.$getdefaultdayrange = getdefaultdayrange vue.prototype.$timeformatting = timeformatting vue.prototype.$getbase64 = getbase64 vue.prototype.$getempty = getempty vue.prototype.$getemptyunit = getemptyunit vue.prototype.$findobjectbyvalue = findobjectbyvalue vue.prototype.$tenmonthsago = tenmonthsago vue.prototype.$timetypeformatting = timetypeformatting vue.prototype.$timeformattype = timeformattype vue.prototype.$tenmonthshistory = tenmonthshistory vue.prototype.$recentmonths = recentmonths }, }
总结
到此这篇关于vue各种时间类型转换的文章就介绍到这了,更多相关vue时间类型转换内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论