util.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. const formatTime = date => {
  2. const year = date.getFullYear()
  3. const month = date.getMonth() + 1
  4. const day = date.getDate()
  5. const hour = date.getHours()
  6. const minute = date.getMinutes()
  7. const second = date.getSeconds()
  8. return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
  9. }
  10. const formatNumber = n => {
  11. n = n.toString()
  12. return n[1] ? n : '0' + n
  13. }
  14. // 计算时间差
  15. const handleDate = date => {
  16. if (typeof date === 'string') {
  17. date = new Date(date)
  18. }
  19. const diffValue = new Date().getTime() - date.getTime()
  20. if (diffValue < 0) {
  21. console.log('时间不同步')
  22. return '刚刚'
  23. }
  24. const minute = 1000 * 60
  25. const hour = minute * 60
  26. const day = hour * 24
  27. const minC = diffValue / minute
  28. const hourC = diffValue / hour
  29. const dayC = diffValue / day
  30. let result = ''
  31. if (parseInt(dayC) > 3) {
  32. result = date.getFullYear() + '/' + (date.getMonth() + 1) + '/' + date.getDate()
  33. } else if (parseInt(dayC) > 1) {
  34. result = parseInt(dayC) + '天前'
  35. } else if (parseInt(dayC) == 1) {
  36. result = '昨天'
  37. } else if (hourC >= 1) {
  38. result = parseInt(hourC) + '小时前'
  39. } else if (minC >= 3) {
  40. result = parseInt(minC) + '分钟前'
  41. } else {
  42. result = '刚刚'
  43. }
  44. return result
  45. }
  46. const randomString = len => {
  47. const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
  48. let str = '';
  49. for (let i = 0; i < len; i++) {
  50. str += chars[Math.floor(Math.random() * chars.length)]
  51. }
  52. return str
  53. }
  54. const msgToDb = function (item) {
  55. item.type = item.type.join()
  56. item.poster = item.poster.join()
  57. item.photo = item.photo.join()
  58. if (item.tag) {
  59. item.tag = item.tag.join()
  60. }
  61. }
  62. const dbToMsg = function (item) {
  63. item.type = item.type.split(',')
  64. if (item.poster !== '') {
  65. item.poster = item.poster.split(',')
  66. } else {
  67. item.poster = []
  68. }
  69. if (item.photo !== '') {
  70. item.photo = item.photo.split(',')
  71. } else {
  72. item.poster = []
  73. }
  74. if (item.tag !== '') {
  75. item.tag = item.tag.split(',')
  76. } else {
  77. item.tag = []
  78. }
  79. item.publish_time = handleDate(item.publish_time)
  80. return item
  81. }
  82. module.exports = {
  83. formatTime: formatTime,
  84. handleDate: handleDate,
  85. randomString: randomString,
  86. msgToDb: msgToDb,
  87. dbToMsg: dbToMsg
  88. }