index.ts 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. import { parseTime } from '@/utils/ruoyi';
  2. export function dateFormat(date, format = 'yyyy-MM-dd HH:mm:ss') {
  3. const o = {
  4. 'M+': date.getMonth() + 1, // 月份
  5. 'd+': date.getDate(), // 日
  6. 'h+': date.getHours() % 12 === 0 ? 12 : date.getHours() % 12, // 小时
  7. 'H+': date.getHours(), // 小时
  8. 'm+': date.getMinutes(), // 分
  9. 's+': date.getSeconds(), // 秒
  10. 'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
  11. S: date.getMilliseconds(), // 毫秒
  12. a: date.getHours() < 12 ? '上午' : '下午', // 上午/下午
  13. A: date.getHours() < 12 ? 'AM' : 'PM' // AM/PM
  14. };
  15. if (/(y+)/.test(format)) {
  16. format = format.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
  17. }
  18. for (let k in o) {
  19. if (new RegExp('(' + k + ')').test(format)) {
  20. format = format.replace(RegExp.$1, RegExp.$1.length === 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length));
  21. }
  22. }
  23. return format;
  24. }
  25. /**
  26. * 表格时间格式化
  27. */
  28. export const formatDate = (cellValue: string) => {
  29. if (cellValue == null || cellValue == '') return '';
  30. const date = new Date(cellValue);
  31. const year = date.getFullYear();
  32. const month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1;
  33. const day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
  34. const hours = date.getHours() < 10 ? '0' + date.getHours() : date.getHours();
  35. const minutes = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes();
  36. const seconds = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
  37. return year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds;
  38. };
  39. /**
  40. * @param {number} time
  41. * @param {string} option
  42. * @returns {string}
  43. */
  44. export const formatTime = (time: string, option: string) => {
  45. let t: number;
  46. if (('' + time).length === 10) {
  47. t = parseInt(time) * 1000;
  48. } else {
  49. t = +time;
  50. }
  51. const d: any = new Date(t);
  52. const now = Date.now();
  53. const diff = (now - d) / 1000;
  54. if (diff < 30) {
  55. return '刚刚';
  56. } else if (diff < 3600) {
  57. // less 1 hour
  58. return Math.ceil(diff / 60) + '分钟前';
  59. } else if (diff < 3600 * 24) {
  60. return Math.ceil(diff / 3600) + '小时前';
  61. } else if (diff < 3600 * 24 * 2) {
  62. return '1天前';
  63. }
  64. if (option) {
  65. return parseTime(t, option);
  66. } else {
  67. return d.getMonth() + 1 + '月' + d.getDate() + '日' + d.getHours() + '时' + d.getMinutes() + '分';
  68. }
  69. };
  70. /**
  71. * @param {string} url
  72. * @returns {Object}
  73. */
  74. export const getQueryObject = (url: string) => {
  75. url = url == null ? window.location.href : url;
  76. const search = url.substring(url.lastIndexOf('?') + 1);
  77. const obj: { [key: string]: string } = {};
  78. const reg = /([^?&=]+)=([^?&=]*)/g;
  79. search.replace(reg, (rs, $1, $2) => {
  80. const name = decodeURIComponent($1);
  81. let val = decodeURIComponent($2);
  82. val = String(val);
  83. obj[name] = val;
  84. return rs;
  85. });
  86. return obj;
  87. };
  88. /**
  89. * @param {string} input value
  90. * @returns {number} output value
  91. */
  92. export const byteLength = (str: string) => {
  93. // returns the byte length of an utf8 string
  94. let s = str.length;
  95. for (let i = str.length - 1; i >= 0; i--) {
  96. const code = str.charCodeAt(i);
  97. if (code > 0x7f && code <= 0x7ff) s++;
  98. else if (code > 0x7ff && code <= 0xffff) s += 2;
  99. if (code >= 0xdc00 && code <= 0xdfff) i--;
  100. }
  101. return s;
  102. };
  103. /**
  104. * @param {Array} actual
  105. * @returns {Array}
  106. */
  107. export const cleanArray = (actual: Array<any>) => {
  108. const newArray: any[] = [];
  109. for (let i = 0; i < actual.length; i++) {
  110. if (actual[i]) {
  111. newArray.push(actual[i]);
  112. }
  113. }
  114. return newArray;
  115. };
  116. /**
  117. * @param {Object} json
  118. * @returns {Array}
  119. */
  120. export const param = (json: any) => {
  121. if (!json) return '';
  122. return cleanArray(
  123. Object.keys(json).map((key) => {
  124. if (json[key] === undefined) return '';
  125. return encodeURIComponent(key) + '=' + encodeURIComponent(json[key]);
  126. })
  127. ).join('&');
  128. };
  129. /**
  130. * @param {string} url
  131. * @returns {Object}
  132. */
  133. export const param2Obj = (url: string) => {
  134. const search = decodeURIComponent(url.split('?')[1]).replace(/\+/g, ' ');
  135. if (!search) {
  136. return {};
  137. }
  138. const obj: any = {};
  139. const searchArr = search.split('&');
  140. searchArr.forEach((v) => {
  141. const index = v.indexOf('=');
  142. if (index !== -1) {
  143. const name = v.substring(0, index);
  144. const val = v.substring(index + 1, v.length);
  145. obj[name] = val;
  146. }
  147. });
  148. return obj;
  149. };
  150. /**
  151. * @param {string} val
  152. * @returns {string}
  153. */
  154. export const html2Text = (val: string) => {
  155. const div = document.createElement('div');
  156. div.innerHTML = val;
  157. return div.textContent || div.innerText;
  158. };
  159. /**
  160. * Merges two objects, giving the last one precedence
  161. * @param {Object} target
  162. * @param {(Object|Array)} source
  163. * @returns {Object}
  164. */
  165. export const objectMerge = (target: any, source: any | any[]) => {
  166. if (typeof target !== 'object') {
  167. target = {};
  168. }
  169. if (Array.isArray(source)) {
  170. return source.slice();
  171. }
  172. Object.keys(source).forEach((property) => {
  173. const sourceProperty = source[property];
  174. if (typeof sourceProperty === 'object') {
  175. target[property] = objectMerge(target[property], sourceProperty);
  176. } else {
  177. target[property] = sourceProperty;
  178. }
  179. });
  180. return target;
  181. };
  182. /**
  183. * @param {HTMLElement} element
  184. * @param {string} className
  185. */
  186. export const toggleClass = (element: HTMLElement, className: string) => {
  187. if (!element || !className) {
  188. return;
  189. }
  190. let classString = element.className;
  191. const nameIndex = classString.indexOf(className);
  192. if (nameIndex === -1) {
  193. classString += '' + className;
  194. } else {
  195. classString = classString.substring(0, nameIndex) + classString.substring(nameIndex + className.length);
  196. }
  197. element.className = classString;
  198. };
  199. /**
  200. * @param {string} type
  201. * @returns {Date}
  202. */
  203. export const getTime = (type: string) => {
  204. if (type === 'start') {
  205. return new Date().getTime() - 3600 * 1000 * 24 * 90;
  206. } else {
  207. return new Date(new Date().toDateString());
  208. }
  209. };
  210. /**
  211. * @param {Function} func
  212. * @param {number} wait
  213. * @param {boolean} immediate
  214. * @return {*}
  215. */
  216. export const debounce = (func: any, wait: number, immediate: boolean) => {
  217. let timeout: any, args: any, context: any, timestamp: any, result: any;
  218. const later = function () {
  219. // 据上一次触发时间间隔
  220. const last = +new Date() - timestamp;
  221. // 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
  222. if (last < wait && last > 0) {
  223. timeout = setTimeout(later, wait - last);
  224. } else {
  225. timeout = null;
  226. // 如果设定为immediate===true,因为开始边界已经调用过了此处无需调用
  227. if (!immediate) {
  228. result = func.apply(context, args);
  229. if (!timeout) context = args = null;
  230. }
  231. }
  232. };
  233. return (...args: any) => {
  234. context = this;
  235. timestamp = +new Date();
  236. const callNow = immediate && !timeout;
  237. // 如果延时不存在,重新设定延时
  238. if (!timeout) timeout = setTimeout(later, wait);
  239. if (callNow) {
  240. result = func.apply(context, args);
  241. context = args = null;
  242. }
  243. return result;
  244. };
  245. };
  246. /**
  247. * This is just a simple version of deep copy
  248. * Has a lot of edge cases bug
  249. * If you want to use a perfect deep copy, use lodash's _.cloneDeep
  250. * @param {Object} source
  251. * @returns {Object}
  252. */
  253. export const deepClone = (source: any) => {
  254. if (!source && typeof source !== 'object') {
  255. throw new Error('error arguments', 'deepClone' as any);
  256. }
  257. const targetObj: any = source.constructor === Array ? [] : {};
  258. Object.keys(source).forEach((keys) => {
  259. if (source[keys] && typeof source[keys] === 'object') {
  260. targetObj[keys] = deepClone(source[keys]);
  261. } else {
  262. targetObj[keys] = source[keys];
  263. }
  264. });
  265. return targetObj;
  266. };
  267. /**
  268. * @param {Array} arr
  269. * @returns {Array}
  270. */
  271. export const uniqueArr = (arr: any) => {
  272. return Array.from(new Set(arr));
  273. };
  274. /**
  275. * @returns {string}
  276. */
  277. export const createUniqueString = (): string => {
  278. const timestamp = +new Date() + '';
  279. const num = (1 + Math.random()) * 65536;
  280. const randomNum = parseInt(num + '');
  281. return (+(randomNum + timestamp)).toString(32);
  282. };
  283. /**
  284. * Check if an element has a class
  285. * @param ele
  286. * @param {string} cls
  287. * @returns {boolean}
  288. */
  289. export const hasClass = (ele: HTMLElement, cls: string): boolean => {
  290. return !!ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'));
  291. };
  292. /**
  293. * Add class to element
  294. * @param ele
  295. * @param {string} cls
  296. */
  297. export const addClass = (ele: HTMLElement, cls: string) => {
  298. if (!hasClass(ele, cls)) ele.className += ' ' + cls;
  299. };
  300. /**
  301. * Remove class from element
  302. * @param ele
  303. * @param {string} cls
  304. */
  305. export const removeClass = (ele: HTMLElement, cls: string) => {
  306. if (hasClass(ele, cls)) {
  307. const reg = new RegExp('(\\s|^)' + cls + '(\\s|$)');
  308. ele.className = ele.className.replace(reg, ' ');
  309. }
  310. };
  311. /**
  312. * @param {string} path
  313. * @returns {Boolean}
  314. */
  315. export const isExternal = (path: string) => {
  316. return /^(https?:|http?:|mailto:|tel:)/.test(path);
  317. };