• vue各种时间类型转换


     时间范围['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']  默认值

    1. function getDateString (date, fmt = 'yyyy-MM-dd') {
    2. if (/(y+)/.test(fmt)) {
    3. fmt = fmt.replace(
    4. RegExp.$1,
    5. (date.getFullYear() + '').substr(4 - RegExp.$1.length)
    6. )
    7. }
    8. let o = {
    9. 'M+': date.getMonth() + 1,
    10. 'd+': date.getDate(),
    11. 'h+': date.getHours(),
    12. 'm+': date.getMinutes(),
    13. 's+': date.getSeconds(),
    14. }
    15. for (let k in o) {
    16. if (new RegExp(`(${k})`).test(fmt)) {
    17. let str = o[k] + ''
    18. fmt = fmt.replace(
    19. RegExp.$1,
    20. RegExp.$1.length === 1 ? str : padLeftZero(str)
    21. )
    22. }
    23. }
    24. return fmt
    25. }
    26. export function getRecentDays (duration = 7, fmt = 'yyyy-MM-dd hh:mm:ss') {
    27. let oneDayLong = 24 * 60 * 60 * 1000
    28. let nowTime = Date.now()
    29. let pre7DayTime = nowTime - duration * oneDayLong
    30. let now = new Date(nowTime)
    31. let pre7Day = new Date(pre7DayTime)
    32. return [getDateString(pre7Day, fmt), getDateString(now, fmt)]
    33. }

      开始时间结束时间['2024-04-17 00:00:00', '2024-04-24 23:59:59']

    console.log(this.$todayTimer(30)); 也是可以自定义范围呢

    1. export function todayTimer (duration = 7, fmt = 'yyyy-MM-dd') {
    2. let oneDayLong = 24 * 60 * 60 * 1000
    3. let nowTime = Date.now()
    4. let pre7DayTime = nowTime - duration * oneDayLong
    5. let now = new Date(nowTime)
    6. let pre7Day = new Date(pre7DayTime)
    7. return [
    8. getDateString(pre7Day, fmt) + ' ' + '00:00:00',
    9. getDateString(now, fmt) + ' ' + '23:59:59',
    10. ]
    11. }

    今年的起始时间 和结束时间 ['2024-01-01 00:00:00', '2024-12-31 23:59:59']

    1. export function todayTimer (duration = 7, fmt = 'yyyy-MM-dd') {
    2. let oneDayLong = 24 * 60 * 60 * 1000
    3. let nowTime = Date.now()
    4. let pre7DayTime = nowTime - duration * oneDayLong
    5. let now = new Date(nowTime)
    6. let pre7Day = new Date(pre7DayTime)
    7. return [
    8. getDateString(pre7Day, fmt) + ' ' + '00:00:00',
    9. getDateString(now, fmt) + ' ' + '23:59:59',
    10. ]
    11. }

     当月的开始结束时间 ['2024-04-01 00:00:00', '2024-04-30 23:59:59']

    1. export function ofMonth () {
    2. const startOfMonth = moment().startOf('month').format('YYYY-MM-DD 00:00:00'); // 本月的起始时间
    3. const endOfMonth = moment().endOf('month').format('YYYY-MM-DD 23:59:59'); // 本月的结束时间
    4. return [startOfMonth, endOfMonth]
    5. }

     最近几个月 ['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));

    1. export function recentMonths (type, val) {
    2. const now = moment();
    3. if (type == 'day') {
    4. const startDate = now.clone().subtract(val - 1, 'days').startOf('day');
    5. const endDate = now.clone().endOf('day').hours(23).minutes(59).seconds(59);
    6. const dayRange = [startDate.format('YYYY-MM-DD HH:mm:ss'), endDate.format('YYYY-MM-DD HH:mm:ss')];
    7. return dayRange;
    8. }
    9. if (type == 'week') {
    10. const weeksAgo = now.clone().subtract(val - 1, 'weeks').startOf('isoWeek');
    11. const thisWeekEnd = now.clone().endOf('week').hours(23).minutes(59).seconds(59);
    12. const recentWeeksRange = [weeksAgo.format('YYYY-MM-DD HH:mm:ss'), thisWeekEnd.format('YYYY-MM-DD HH:mm:ss')];
    13. // console.log(recentWeeksRange);
    14. return recentWeeksRange;
    15. }
    16. if (type == 'month') {
    17. const sixMonthsAgo = now.clone().subtract(val, 'months').endOf('month').startOf('day');
    18. const thisMonthEnd = now.clone().endOf('month').hours(23).minutes(59).seconds(59);
    19. const recentSixMonthsRange = [
    20. sixMonthsAgo.format('YYYY-MM-DD HH:mm:ss'),
    21. thisMonthEnd.format('YYYY-MM-DD HH:mm:ss')
    22. ]
    23. return recentSixMonthsRange
    24. }
    25. }

    各种时间类型就不一一列了    

    下面是完整的js代码

    1. import * as moment from 'moment';
    2. moment.suppressDeprecationWarnings = true;
    3. // 封装的 一些关于时间的方法
    4. function random (low, high) {
    5. if (arguments.length === 1) {
    6. high = low
    7. low = 0
    8. }
    9. return Math.floor(low + Math.random() * (high - low))
    10. }
    11. function randomOne (arr) {
    12. return arr[random(arr.length)]
    13. }
    14. function getDateString (date, fmt = 'yyyy-MM-dd') {
    15. if (/(y+)/.test(fmt)) {
    16. fmt = fmt.replace(
    17. RegExp.$1,
    18. (date.getFullYear() + '').substr(4 - RegExp.$1.length)
    19. )
    20. }
    21. let o = {
    22. 'M+': date.getMonth() + 1,
    23. 'd+': date.getDate(),
    24. 'h+': date.getHours(),
    25. 'm+': date.getMinutes(),
    26. 's+': date.getSeconds(),
    27. }
    28. for (let k in o) {
    29. if (new RegExp(`(${k})`).test(fmt)) {
    30. let str = o[k] + ''
    31. fmt = fmt.replace(
    32. RegExp.$1,
    33. RegExp.$1.length === 1 ? str : padLeftZero(str)
    34. )
    35. }
    36. }
    37. return fmt
    38. }
    39. function getDateStringCh (date) {
    40. if (!(date instanceof Date)) {
    41. return ''
    42. }
    43. let year = date.getFullYear()
    44. let month = date.getMonth() + 1
    45. let day = date.getDate()
    46. let hour = date.getHours()
    47. return `${year}年${month}月${day}日 ${hour}时`
    48. }
    49. function getWeekStartDateAndEndDateRange () {
    50. let oneDayLong = 24 * 60 * 60 * 1000
    51. let now = new Date()
    52. let mondayTime = now.getTime() - (now.getDay() - 1) * oneDayLong
    53. let sundayTime = now.getTime() + (7 - now.getDay()) * oneDayLong
    54. let monday = new Date(mondayTime)
    55. let sunday = new Date(sundayTime)
    56. let weekRange = [getDateString(monday), getDateString(sunday)]
    57. return weekRange
    58. }
    59. // ['2024-04-17 14:36:27', '2024-04-24 14:36:27'] 默认值
    60. // console.log(this.$getRecentDays()); 页面使用
    61. export function getRecentDays (duration = 7, fmt = 'yyyy-MM-dd hh:mm:ss') {
    62. let oneDayLong = 24 * 60 * 60 * 1000
    63. let nowTime = Date.now()
    64. let pre7DayTime = nowTime - duration * oneDayLong
    65. let now = new Date(nowTime)
    66. let pre7Day = new Date(pre7DayTime)
    67. return [getDateString(pre7Day, fmt), getDateString(now, fmt)]
    68. }
    69. function getMonthStartDateAndDateRange () {
    70. let oneDayLong = 24 * 60 * 60 * 1000
    71. let now = new Date()
    72. let year = now.getFullYear()
    73. let monthStartDate = new Date(year, now.getMonth(), 1) //当前月1
    74. let nextMonthStartDate = new Date(year, now.getMonth() + 1, 1) //下个月1
    75. let days =
    76. (nextMonthStartDate.getTime() - monthStartDate.getTime()) / oneDayLong //计算当前月份的天数
    77. let monthEndDate = new Date(year, now.getMonth(), days)
    78. let monthRange = [getDateString(monthStartDate), getDateString(monthEndDate)]
    79. return monthRange
    80. }
    81. function padLeftZero (str) {
    82. return ('00' + str).substr(str.length)
    83. }
    84. function resetForm (refName) {
    85. this.$refs[refName] && this.$refs[refName].resetFields()
    86. }
    87. export function debounce (func, wait, immediate) {
    88. let timeout, args, context, timestamp, result
    89. const later = function () {
    90. // 据上一次触发时间间隔
    91. const last = +new Date() - timestamp
    92. // 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
    93. if (last < wait && last > 0) {
    94. timeout = setTimeout(later, wait - last)
    95. } else {
    96. timeout = null
    97. // 如果设定为immediate===true,因为开始边界已经调用过了此处无需调用
    98. if (!immediate) {
    99. result = func.apply(context, args)
    100. if (!timeout) context = args = null
    101. }
    102. }
    103. }
    104. return function (...args) {
    105. context = this
    106. timestamp = +new Date()
    107. const callNow = immediate && !timeout
    108. // 如果延时不存在,重新设定延时
    109. if (!timeout) timeout = setTimeout(later, wait)
    110. if (callNow) {
    111. result = func.apply(context, args)
    112. context = args = null
    113. }
    114. return result
    115. }
    116. }
    117. // console.log(this.$randomUUID());
    118. // 1713940662895.5952 数据数
    119. function randomUUID () {
    120. return Date.now() + Math.random() + ''
    121. }
    122. const resetTimer = (timer) => {
    123. if (timer) {
    124. clearTimeout(timer)
    125. timer = null
    126. }
    127. }
    128. // ['2024-04-17 00:00:00', '2024-04-24 23:59:59'] 开始时间结束时间
    129. export function todayTimer (duration = 7, fmt = 'yyyy-MM-dd') {
    130. let oneDayLong = 24 * 60 * 60 * 1000
    131. let nowTime = Date.now()
    132. let pre7DayTime = nowTime - duration * oneDayLong
    133. let now = new Date(nowTime)
    134. let pre7Day = new Date(pre7DayTime)
    135. return [
    136. getDateString(pre7Day, fmt) + ' ' + '00:00:00',
    137. getDateString(now, fmt) + ' ' + '23:59:59',
    138. ]
    139. }
    140. // 今年的起始时间 和结束时间 ['2024-01-01 00:00:00', '2024-12-31 23:59:59']
    141. export function ofYear () {
    142. const startOfYear = moment().startOf('year').format('YYYY-MM-DD 00:00:00');
    143. const endOfYear = moment().endOf('year').format('YYYY-MM-DD 23:59:59');
    144. return [startOfYear, endOfYear]
    145. }
    146. // 这个月的开始结束时间 ['2024-04-01 00:00:00', '2024-04-30 23:59:59']
    147. export function ofMonth () {
    148. const startOfMonth = moment().startOf('month').format('YYYY-MM-DD 00:00:00'); // 本月的起始时间
    149. const endOfMonth = moment().endOf('month').format('YYYY-MM-DD 23:59:59'); // 本月的结束时间
    150. return [startOfMonth, endOfMonth]
    151. }
    152. // 上传json;模板
    153. export function funDownload (content, filename) {
    154. // 创建隐藏的可下载链接
    155. const eleLink = document.createElement('a')
    156. eleLink.download = filename
    157. eleLink.style.display = 'none'
    158. // 字符内容转变成blob地址
    159. let blob = new Blob([content])
    160. eleLink.href = URL.createObjectURL(blob)
    161. // 触发点击
    162. document.body.appendChild(eleLink)
    163. eleLink.click()
    164. // 然后移除
    165. document.body.removeChild(eleLink)
    166. }
    167. // 对象转json字符串
    168. export function objToJson (obj) {
    169. let newObj = {}
    170. for (let key in obj) {
    171. if (key === 'id') {
    172. newObj[key] = obj[key]
    173. continue
    174. }
    175. newObj[key] = JSON.stringify(obj[key])
    176. }
    177. return newObj
    178. }
    179. // 打印
    180. export function print (id) {
    181. var bdhtml = window.document.body.innerHTML
    182. var jubuData = document.getElementById(id).innerHTML
    183. window.document.body.innerHTML = jubuData
    184. var style = document.createElement('style');
    185. style.innerHTML = `
    186. @media print {
    187. @page {
    188. size: auto;
    189. margin: 5mm;
    190. }
    191. body {
    192. margin: 0;
    193. }
    194. .no-print {
    195. display: none;
    196. }
    197. .el-divider {
    198. border: 1px solid #dcdfe6;
    199. margin: 24px 0;
    200. }
    201. }
    202. `;
    203. document.head.appendChild(style);
    204. const table = document.querySelectorAll(".el-table__header,.el-table__body,.el-table__footer");
    205. for (let i = 0; i < table.length; i++) {
    206. const tableItem = table[i];
    207. tableItem.style.width = '100%';
    208. const child = tableItem.childNodes;
    209. for (let j = 0; j < child.length; j++) {
    210. const element = child[j];
    211. if (element.localName == 'colgroup') {
    212. element.innerHTML = '';
    213. }
    214. }
    215. }
    216. window.print()
    217. location.reload()
    218. document.head.removeChild(style);
    219. window.document.body.innerHTML = bdhtml
    220. }
    221. // 打印图片
    222. export function printCanvas (id, i) {
    223. var oldstr = document.body.innerHTML // 获取当前页面内容用以还原
    224. var div_print = document.getElementById(id) // 获取要打印部分的内容
    225. var cv = document.getElementsByTagName('canvas')[i] //获取canvas
    226. var resImg = document.getElementById(id) //获取包裹canvas的标签
    227. // 将canvas转为图片
    228. // var context = cv.getContext("2d")
    229. var img = new Image()
    230. var strDataURI = cv.toDataURL('image/png')
    231. img.src = strDataURI
    232. // 图片加载完成之后
    233. img.onload = function () {
    234. // 执行打印
    235. console.log(img);
    236. setTimeout(function () {
    237. resImg.innerHTML = `<img src="${strDataURI}">` // 用图片替代canvas
    238. var newstr = div_print.innerHTML
    239. document.body.innerHTML = newstr // 将页面内容改为修改后的内容
    240. window.print() // 打印
    241. window.location.reload() // 重新加载页面
    242. document.body.innerHTML = oldstr // 将页面内容还原
    243. }, 1000)
    244. }
    245. }
    246. // 下载echarts为图片
    247. export function exportpic (chartInstance, name = 'charts') {
    248. let picInfo = chartInstance.getDataURL({
    249. type: 'png',
    250. pixelRatio: 2, //放大两倍下载,之后压缩到同等大小展示。解决生成图片在移动端模糊问题
    251. backgroundColor: '#fff'
    252. });//获取到的是一串base64信息
    253. const elink = document.createElement('a');
    254. elink.download = name + '.png';
    255. elink.style.display = 'none';
    256. elink.href = picInfo;
    257. document.body.appendChild(elink);
    258. elink.click();
    259. URL.revokeObjectURL(elink.href); // 释放URL 对象
    260. document.body.removeChild(elink)
    261. }
    262. // 复制
    263. export function copyText (row, column, cell, event) {
    264. // 双击复制
    265. let save = function (e) {
    266. e.clipboardData.setData('text/plain', event.target.innerText);
    267. e.preventDefault(); //阻止默认行为
    268. }
    269. document.addEventListener('copy', save);//添加一个copy事件
    270. document.execCommand("copy");//执行copy方法
    271. this.$message({ message: '复制成功', type: 'success' })//提示
    272. }
    273. // ['2024-04-23 14:39:48', '2024-04-24 14:39:48']
    274. export function getDefaultTimeRange (type = "real", val, fmt = 'yyyy-MM-dd hh:mm:ss') {
    275. let start = new Date()
    276. if (type === 'real') {
    277. start.setDate(start.getDate() - (val ? val : 1))
    278. }
    279. if (type === 'hour') {
    280. start.setDate(start.getDate() - (val ? val : 1))
    281. }
    282. if (type === 'day') {
    283. start.setMonth(start.getMonth() - (val ? val : 1))
    284. }
    285. if (type === 'week') {
    286. start.setMonth(start.getMonth() - (val ? val : 3))
    287. }
    288. if (type === 'month') {
    289. start.setFullYear(start.getFullYear() - (val ? val : 1))
    290. }
    291. if (type === 'quarter') {
    292. val = val || 3; // 如果val未提供,则默认为3
    293. start.setFullYear(start.getFullYear() - Math.floor(val / 4));
    294. start.setMonth(start.getMonth() - (val % 4) * 3);
    295. }
    296. if (type === 'year') {
    297. start.setFullYear(start.getFullYear() - (val ? val : 10))
    298. }
    299. return [getDateString(start, fmt), getDateString(new Date(), fmt)]
    300. }
    301. // ['2024-04-24 00:00:00', '2024-04-24 23:59:59'] 一天结束或开始
    302. export function getDefaultDayRange (type = "real", fmt = 'yyyy-MM-dd hh:mm:ss') {
    303. let start = new Date()
    304. let end = new Date()
    305. if (type === 'real') {
    306. start.setDate(start.getDate())
    307. end.setDate(start.getDate())
    308. }
    309. if (type === 'hour') {
    310. start.setDate(start.getDate())
    311. end.setDate(start.getDate())
    312. }
    313. if (type === 'day') {
    314. start.setDate(1)
    315. end.setMonth(end.getMonth() + 1)
    316. end.setDate(0)
    317. }
    318. if (type === 'month') {
    319. start.setDate(1)
    320. start.setMonth(0)
    321. end.setFullYear(end.getFullYear() + 1)
    322. end.setMonth(0)
    323. end.setDate(0)
    324. }
    325. return [getDateString(start, fmt).split(' ')[0] + ' 00:00:00', getDateString(end, fmt).split(' ')[0] + ' 23:59:59']
    326. }
    327. // 最近几个月 ['2023-10-31 00:00:00', '2024-04-30 23:59:59']
    328. // console.log(this.$recentMonths('month',6));
    329. export function recentMonths (type, val) {
    330. const now = moment();
    331. if (type == 'day') {
    332. const startDate = now.clone().subtract(val - 1, 'days').startOf('day');
    333. const endDate = now.clone().endOf('day').hours(23).minutes(59).seconds(59);
    334. const dayRange = [startDate.format('YYYY-MM-DD HH:mm:ss'), endDate.format('YYYY-MM-DD HH:mm:ss')];
    335. return dayRange;
    336. }
    337. if (type == 'week') {
    338. const weeksAgo = now.clone().subtract(val - 1, 'weeks').startOf('isoWeek');
    339. const thisWeekEnd = now.clone().endOf('week').hours(23).minutes(59).seconds(59);
    340. const recentWeeksRange = [weeksAgo.format('YYYY-MM-DD HH:mm:ss'), thisWeekEnd.format('YYYY-MM-DD HH:mm:ss')];
    341. // console.log(recentWeeksRange);
    342. return recentWeeksRange;
    343. }
    344. if (type == 'month') {
    345. const sixMonthsAgo = now.clone().subtract(val, 'months').endOf('month').startOf('day');
    346. const thisMonthEnd = now.clone().endOf('month').hours(23).minutes(59).seconds(59);
    347. const recentSixMonthsRange = [
    348. sixMonthsAgo.format('YYYY-MM-DD HH:mm:ss'),
    349. thisMonthEnd.format('YYYY-MM-DD HH:mm:ss')
    350. ]
    351. return recentSixMonthsRange
    352. }
    353. }
    354. // 参数为秒 返回时间
    355. // console.log(this.$timeRangeFormat(600)); 10分钟
    356. export function timeRangeFormat (seconds) {
    357. const timeUnits = [
    358. {
    359. label: '天',
    360. value: Math.floor(seconds / (24 * 3600))
    361. },
    362. {
    363. label: '小时',
    364. value: Math.floor((seconds % (24 * 3600)) / 3600)
    365. },
    366. {
    367. label: '分钟',
    368. value: Math.floor((seconds % 3600) / 60)
    369. },
    370. {
    371. label: '秒',
    372. value: Math.floor(seconds % 60)
    373. }
    374. ]
    375. return timeUnits.filter(v => v.value > 0).map(item => `${item.value}${item.label}`).join('').trim()
    376. }
    377. // {startDateTime: '2023-03-03 00:00:00', endDateTime: '2023-03-03 23:59:59'}
    378. // console.log(this.$timeRange('day','2023-03-03'));
    379. export function timeRange (type, val) {
    380. let startDateTime, endDateTime;
    381. switch (type) {
    382. case 'hour':
    383. startDateTime = moment(val).startOf('hour');
    384. endDateTime = moment(val).endOf('hour');
    385. break;
    386. case 'day':
    387. startDateTime = moment(val).startOf('day');
    388. endDateTime = moment(val).endOf('day');
    389. break;
    390. case 'week':
    391. let value = val.toString()
    392. const weekYear = value.substring(0, 4)
    393. const weekNumber = value.substring(4, 6)
    394. startDateTime = moment().isoWeekYear(parseInt(weekYear)).isoWeek(parseInt(weekNumber)).startOf('isoWeek');
    395. endDateTime = moment().isoWeekYear(parseInt(weekYear)).isoWeek(parseInt(weekNumber)).endOf('isoWeek');
    396. break;
    397. case 'month':
    398. startDateTime = moment(val, "YYYY-MM").startOf('month');
    399. endDateTime = moment(val, "YYYY-MM").endOf('month');
    400. break;
    401. case 'quarter':
    402. let valSeason = val.toString()
    403. const year = valSeason.substring(0, 4)
    404. const quarter = valSeason.substring(4, 5)
    405. startDateTime = moment().quarter(quarter).year(year).startOf('quarter');
    406. endDateTime = moment().quarter(quarter).year(year).endOf('quarter');
    407. break;
    408. case 'year':
    409. startDateTime = moment(val, "YYYY").startOf('year');
    410. endDateTime = moment(val, "YYYY").endOf('year');
    411. break;
    412. default:
    413. return;
    414. }
    415. startDateTime = startDateTime.format("YYYY-MM-DD HH:mm:ss");
    416. endDateTime = endDateTime.format("YYYY-MM-DD HH:mm:ss");
    417. return { startDateTime, endDateTime };
    418. }
    419. export function timeFormatting (type, val) {
    420. if (type == 'hour') {
    421. let hour = moment().set({ hour: val, minute: 0, second: 0, millisecond: 0 }).format('YYYY-MM-DD HH');
    422. return hour
    423. } else if (type == 'day') {
    424. let day = moment().date(val).format('YYYY-MM-DD');
    425. return day
    426. } else if (type == 'month') {
    427. let month = moment(val, 'MM').format('YYYY-MM');
    428. return month
    429. }
    430. }
    431. // console.log(this.$timeFormatType('day', '2023123')); 2023-12-03
    432. export function timeFormatType (type, val) {
    433. if (type == 'hour') {
    434. let [year, month, date, hour] = String(val).split(/(\d{4})(\d{2})(\d{2})(\d{2})/).slice(1);
    435. // 创建moment对象并设置时间
    436. let momentDate = moment().set({ year: parseInt(year), month: parseInt(month) - 1, date: parseInt(date), hour: parseInt(hour), minute: 0, second: 0, millisecond: 0 });
    437. // 格式化时间
    438. let hourVal = momentDate.format('YYYY-MM-DD HH');
    439. return hourVal
    440. } else if (type == 'day') {
    441. let day = moment(val, 'YYYYMMDD').format('YYYY-MM-DD');
    442. return day
    443. } else if (type == 'month') {
    444. const month = moment(val, 'YYYYMM').format('YYYY-MM');
    445. return month
    446. } else if (type == 'year') {
    447. const year = moment(val, 'YYYY').format('YYYY');
    448. return year
    449. } else if (type == 'week') {
    450. const weekYear = val.toString().substring(0, 4);
    451. const weekNum = val.toString().substring(4);
    452. const startDate = moment(`${weekYear}-01-01`).add((weekNum) * 7, 'days').startOf('isoWeek');
    453. let week = startDate.format('YYYY-WW');
    454. return week
    455. } else if (type == 'quarter') {
    456. const quarterYear = val.toString().substring(0, 4);
    457. const quarterNum = val.toString().substring(4);
    458. // 计算季度的第一天日期
    459. const startDate = moment(`${quarterYear}-01-01`).add((quarterNum - 1) * 3, 'months').startOf('month');
    460. let quarter = startDate.format('YYYY-Q');
    461. return quarter
    462. }
    463. }
    464. // console.log(this.$tenMonthsAgo(24, 'month'));
    465. // ['2022-04', '2024-04']
    466. export function tenMonthsAgo (val, type) {
    467. if (type == 'hour') {
    468. return hour
    469. } else if (type == 'day') {
    470. return day
    471. } else if (type == 'month') {
    472. const tenMonthsAgo = moment().subtract(val, 'months').format('YYYY-MM');
    473. const currentMonth = moment().format('YYYY-MM');
    474. const month = [tenMonthsAgo, currentMonth];
    475. return month
    476. }
    477. }
    478. export function tenMonthsHistory (val, type) {
    479. if (type == 'hour') {
    480. return hour
    481. } else if (type == 'day') {
    482. return day
    483. } else if (type == 'month') {
    484. const tenMonthsAgo = moment().subtract(val, 'months').format('YYYY-MM');
    485. const currentMonth = moment().subtract(1, 'months').format('YYYY-MM');
    486. const month = [tenMonthsAgo, currentMonth];
    487. return month
    488. }
    489. }
    490. // 20240101 console.log(this.$timeTypeFormatting('day', '2024-01-01'),);
    491. export function timeTypeFormatting (type, value) {
    492. switch (type) {
    493. case 'hour':
    494. return value.substring(0, 13).replace(/[- :]/g, "");
    495. break;
    496. case 'day':
    497. return value.replace(/[- :]/g, "");
    498. break;
    499. case 'week':
    500. return (moment(value).isoWeekYear() + ' ' + moment(value).isoWeek()).replace(/[- :]/g, "");
    501. break;
    502. case 'month':
    503. return value.replace(/[- :]/g, "");
    504. break;
    505. case 'year':
    506. return value.replace(/[- :]/g, "");
    507. break;
    508. default: '';
    509. }
    510. }
    511. export function getBase64 (file) {
    512. return new Promise(function (resolve, reject) {
    513. const reader = new FileReader()
    514. let imgResult = ''
    515. reader.readAsDataURL(file)
    516. reader.onload = function () {
    517. imgResult = reader.result
    518. }
    519. reader.onerror = function (error) {
    520. reject(error)
    521. }
    522. reader.onloadend = function () {
    523. resolve(imgResult)
    524. }
    525. })
    526. }
    527. export function getEmpty (val) {
    528. if (val !== null && val !== false && val !== undefined && val !== NaN && val !== '') {
    529. return val
    530. } else {
    531. return '-'
    532. }
    533. }
    534. export function getEmptyUnit (val, unit) {
    535. if (val !== null && val !== false && val !== undefined && val !== NaN && val !== '' && val != '0.00' && val !== 0 && val && val !== 'NaN') {
    536. return unit
    537. } else {
    538. return ''
    539. }
    540. }
    541. export function findObjectByValue (arr, val) {
    542. let result = [];
    543. function search (arr, parentObjects = []) {
    544. for (let i = 0; i < arr.length; i++) {
    545. if (arr[i].id === val) {
    546. // 找到匹配项,将当前对象和所有父级对象都添加到结果数组
    547. result.push(...parentObjects, arr[i]);
    548. }
    549. if (arr[i].childs && arr[i].childs.length > 0) {
    550. // 递归搜索子对象,将当前对象添加到父级对象数组中
    551. search(arr[i].childs, [...parentObjects, arr[i]]);
    552. }
    553. }
    554. }
    555. search(arr);
    556. return result;
    557. }
    558. export default {
    559. install (vue) {
    560. this.addGlobalMethods(vue)
    561. },
    562. addGlobalMethods (vue) {
    563. vue.prototype.$random = random
    564. vue.prototype.$resetForm = resetForm
    565. vue.prototype.$randomOne = randomOne
    566. vue.prototype.$getDateString = getDateString
    567. vue.prototype.$getRecentDays = getRecentDays
    568. vue.prototype.$getWeekStartDateAndEndDateRange =
    569. getWeekStartDateAndEndDateRange
    570. vue.prototype.$getMonthStartDateAndDateRange = getMonthStartDateAndDateRange
    571. vue.prototype.$debounce = debounce
    572. vue.prototype.$getDateStringCh = getDateStringCh
    573. vue.prototype.$randomUUID = randomUUID
    574. vue.prototype.$resetTimer = resetTimer
    575. vue.prototype.$todayTimer = todayTimer
    576. vue.prototype.$funDownload = funDownload
    577. vue.prototype.$objToJson = objToJson
    578. vue.prototype.$print = print
    579. vue.prototype.$printCanvas = printCanvas
    580. vue.prototype.$exportpic = exportpic
    581. vue.prototype.$copyText = copyText
    582. vue.prototype.$getDefaultTimeRange = getDefaultTimeRange
    583. vue.prototype.$timeRangeFormat = timeRangeFormat
    584. vue.prototype.$timeRange = timeRange
    585. vue.prototype.$ofYear = ofYear
    586. vue.prototype.$ofMonth = ofMonth
    587. vue.prototype.$getDefaultDayRange = getDefaultDayRange
    588. vue.prototype.$timeFormatting = timeFormatting
    589. vue.prototype.$getBase64 = getBase64
    590. vue.prototype.$getEmpty = getEmpty
    591. vue.prototype.$getEmptyUnit = getEmptyUnit
    592. vue.prototype.$findObjectByValue = findObjectByValue
    593. vue.prototype.$tenMonthsAgo = tenMonthsAgo
    594. vue.prototype.$timeTypeFormatting = timeTypeFormatting
    595. vue.prototype.$timeFormatType = timeFormatType
    596. vue.prototype.$tenMonthsHistory = tenMonthsHistory
    597. vue.prototype.$recentMonths = recentMonths
    598. },
    599. }

  • 相关阅读:
    微信小程序关联组件
    公司如何对电脑软件进行统一管理?
    【uni-app系列】uni-ui扩展组件和uViewUI的安装使用
    训练一个目标检测模型
    Webpack的打包原理
    js递归理解及使用案例
    HVV(护网)蓝队视角的技战法分析
    开源协议、开源贡献协议与OpenHarmony
    抖音小店运营计划书怎么写?运营技巧及入住条件资料
    torchscript相关知识介绍(二)
  • 原文地址:https://blog.csdn.net/weixin_45884508/article/details/138158950