dateUtil.ts 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import { isObject, isString } from '/@/utils/is';
  2. import moment from 'moment';
  3. const DATE_TIME_FORMAT = 'YYYY-MM-DD HH:mm';
  4. const DATE_FORMAT = 'YYYY-MM-DD ';
  5. export function formatToDateTime(date: moment.MomentInput = null): string {
  6. return moment(date).format(DATE_TIME_FORMAT);
  7. }
  8. export function formatToDate(date: moment.MomentInput = null): string {
  9. return moment(date).format(DATE_FORMAT);
  10. }
  11. export const formatAgo = (str: string | number) => {
  12. if (!str) return '';
  13. const date = new Date(Number(str));
  14. const time = new Date().getTime() - date.getTime(); // 现在的时间-传入的时间 = 相差的时间(单位 = 毫秒)
  15. if (time < 0) {
  16. return '';
  17. } else if (time / 1000 < 30) {
  18. return '刚刚';
  19. } else if (time / 1000 < 60) {
  20. return parseInt(String(time / 1000)) + '秒前';
  21. } else if (time / 60000 < 60) {
  22. return parseInt(String(time / 60000)) + '分钟前';
  23. } else if (time / 3600000 < 24) {
  24. return parseInt(String(time / 3600000)) + '小时前';
  25. } else if (time / 86400000 < 31) {
  26. return parseInt(String(time / 86400000)) + '天前';
  27. } else if (time / 2592000000 < 12) {
  28. return parseInt(String(time / 2592000000)) + '月前';
  29. } else {
  30. return parseInt(String(time / 31536000000)) + '年前';
  31. }
  32. };
  33. /**
  34. * @description: 格式化请求参数时间
  35. */
  36. export function formatRequestDate(params: any) {
  37. for (const key in params) {
  38. if (params[key] && params[key]._isAMomentObject) {
  39. params[key] = params[key].format(DATE_TIME_FORMAT);
  40. }
  41. if (isString(key)) {
  42. const value = params[key];
  43. if (value) {
  44. try {
  45. params[key] = isString(value) ? value.trim() : value;
  46. } catch (error) {
  47. throw new Error(error);
  48. }
  49. }
  50. }
  51. if (isObject(params[key])) {
  52. formatRequestDate(params[key]);
  53. }
  54. }
  55. }
  56. export const dateUtil = moment;