index.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. /**
  2. * Parse the time to string
  3. * @param {(Object|string|number)} time
  4. * @param {string} cFormat
  5. * @returns {string | null}
  6. */
  7. export function parseTime(time, cFormat) {
  8. if (arguments.length === 0) {
  9. return null
  10. }
  11. const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  12. let date
  13. if (typeof time === 'object') {
  14. date = time
  15. } else {
  16. if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
  17. time = parseInt(time)
  18. }
  19. if ((typeof time === 'number') && (time.toString().length === 10)) {
  20. time = time * 1000
  21. }
  22. date = new Date(time)
  23. }
  24. const formatObj = {
  25. y: date.getFullYear(),
  26. m: date.getMonth() + 1,
  27. d: date.getDate(),
  28. h: date.getHours(),
  29. i: date.getMinutes(),
  30. s: date.getSeconds(),
  31. a: date.getDay()
  32. }
  33. const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
  34. const value = formatObj[key]
  35. // Note: getDay() returns 0 on Sunday
  36. if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] }
  37. return value.toString().padStart(2, '0')
  38. })
  39. return time_str
  40. }
  41. /**
  42. * @param {number} time
  43. * @param {string} option
  44. * @returns {string}
  45. */
  46. export function formatTime(time, option) {
  47. if (('' + time).length === 10) {
  48. time = parseInt(time) * 1000
  49. } else {
  50. time = +time
  51. }
  52. const d = new Date(time)
  53. const now = Date.now()
  54. const diff = (now - d) / 1000
  55. if (diff < 30) {
  56. return '刚刚'
  57. } else if (diff < 3600) {
  58. // less 1 hour
  59. return Math.ceil(diff / 60) + '分钟前'
  60. } else if (diff < 3600 * 24) {
  61. return Math.ceil(diff / 3600) + '小时前'
  62. } else if (diff < 3600 * 24 * 2) {
  63. return '1天前'
  64. }
  65. if (option) {
  66. return parseTime(time, option)
  67. } else {
  68. return (
  69. d.getMonth() +
  70. 1 +
  71. '月' +
  72. d.getDate() +
  73. '日' +
  74. d.getHours() +
  75. '时' +
  76. d.getMinutes() +
  77. '分'
  78. )
  79. }
  80. }
  81. /**
  82. * @param {string} url
  83. * @returns {Object}
  84. */
  85. export function param2Obj(url) {
  86. const search = url.split('?')[1]
  87. if (!search) {
  88. return {}
  89. }
  90. return JSON.parse(
  91. '{"' +
  92. decodeURIComponent(search)
  93. .replace(/"/g, '\\"')
  94. .replace(/&/g, '","')
  95. .replace(/=/g, '":"')
  96. .replace(/\+/g, ' ') +
  97. '"}'
  98. )
  99. }
  100. //换肤加class函数
  101. export function toggleClass(element, className) {
  102. if (!element || !className) {
  103. return
  104. }
  105. element.className = className;
  106. }