index.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. export function parseTime(time, cFormat) {
  2. if (arguments.length === 0) {
  3. return null
  4. }
  5. const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  6. let date
  7. if (typeof time === 'object') {
  8. date = time
  9. } else {
  10. if (('' + time).length === 10) time = parseInt(time) * 1000
  11. date = new Date(time)
  12. }
  13. const formatObj = {
  14. y: date.getFullYear(),
  15. m: date.getMonth() + 1,
  16. d: date.getDate(),
  17. h: date.getHours(),
  18. i: date.getMinutes(),
  19. s: date.getSeconds(),
  20. a: date.getDay()
  21. }
  22. const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
  23. let value = formatObj[key]
  24. if (key === 'a') return ['一', '二', '三', '四', '五', '六', '日'][value - 1]
  25. if (result.length > 0 && value < 10) {
  26. value = '0' + value
  27. }
  28. return value || 0
  29. })
  30. return time_str
  31. }
  32. export function formatTime(time, option) {
  33. time = +time * 1000
  34. const d = new Date(time)
  35. const now = Date.now()
  36. const diff = (now - d) / 1000
  37. if (diff < 30) {
  38. return '刚刚'
  39. } else if (diff < 3600) { // less 1 hour
  40. return Math.ceil(diff / 60) + '分钟前'
  41. } else if (diff < 3600 * 24) {
  42. return Math.ceil(diff / 3600) + '小时前'
  43. } else if (diff < 3600 * 24 * 2) {
  44. return '1天前'
  45. }
  46. if (option) {
  47. return parseTime(time, option)
  48. } else {
  49. return d.getMonth() + 1 + '月' + d.getDate() + '日' + d.getHours() + '时' + d.getMinutes() + '分'
  50. }
  51. }