date.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /**
  2. * @desc 格式化日期字符串
  3. * @param { Nubmer} - 时间戳
  4. * @returns { String } 格式化后的日期字符串
  5. */
  6. export function formatDate(timestamp) {
  7. // 补全为13位
  8. let arrTimestamp = (timestamp + '').split('');
  9. for (let start = 0; start < 13; start++) {
  10. if (!arrTimestamp[start]) {
  11. arrTimestamp[start] = '0';
  12. }
  13. }
  14. timestamp = arrTimestamp.join('') * 1;
  15. let minute = 1000 * 60;
  16. let hour = minute * 60;
  17. let day = hour * 24;
  18. let month = day * 30;
  19. let now = new Date().getTime();
  20. let diffValue = now - timestamp;
  21. // 如果本地时间反而小于变量时间
  22. if (diffValue < 0) {
  23. return '不久前';
  24. }
  25. // 计算差异时间的量级
  26. let monthC = diffValue / month;
  27. let weekC = diffValue / (7 * day);
  28. let dayC = diffValue / day;
  29. let hourC = diffValue / hour;
  30. let minC = diffValue / minute;
  31. // 数值补0方法
  32. let zero = function (value) {
  33. if (value < 10) {
  34. return '0' + value;
  35. }
  36. return value;
  37. };
  38. // 使用
  39. if (monthC > 4) {
  40. // 超过1年,直接显示年月日
  41. return (function () {
  42. let date = new Date(timestamp);
  43. return date.getFullYear() + '年' + zero(date.getMonth() + 1) + '月' + zero(date.getDate()) + '日';
  44. })();
  45. } else if (monthC >= 1) {
  46. return parseInt(monthC) + '月前';
  47. } else if (weekC >= 1) {
  48. return parseInt(weekC) + '周前';
  49. } else if (dayC >= 1) {
  50. return parseInt(dayC) + '天前';
  51. } else if (hourC >= 1) {
  52. return parseInt(hourC) + '小时前';
  53. } else if (minC >= 1) {
  54. return parseInt(minC) + '分钟前';
  55. }
  56. return '刚刚';
  57. }