util.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. module.exports = {
  55. formatTime: formatTime,
  56. handleDate: handleDate,
  57. randomString: randomString
  58. }