index.js 2.3 KB

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