datetime.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. function relativeDate(dtstr) {
  4. if (!dtstr)
  5. return '暂无数据';
  6. const dt = new Date(dtstr);
  7. const dateTimeStamp = dt.getTime();
  8. const minute = 1000 * 60;
  9. const hour = minute * 60;
  10. const day = hour * 24;
  11. const month = day * 30;
  12. const now = new Date().getTime();
  13. const diffValue = now - dateTimeStamp;
  14. if (diffValue < 0) {
  15. return;
  16. }
  17. const monthC = diffValue / month;
  18. const weekC = diffValue / (7 * day);
  19. const dayC = diffValue / day;
  20. const hourC = diffValue / hour;
  21. const minC = diffValue / minute;
  22. let result;
  23. if (monthC > 12) {
  24. const y = dt.getFullYear() + ' 年';
  25. const m = dt.getMonth() + 1 + ' 月';
  26. const d = dt.getDate() + ' 日';
  27. result = [y, m, d].join(' ');
  28. }
  29. else if (monthC >= 1) {
  30. result = '' + Math.floor(monthC) + ' 个月前';
  31. }
  32. else if (weekC >= 1) {
  33. result = '' + Math.floor(weekC) + ' 周前';
  34. }
  35. else if (dayC >= 1) {
  36. result = '' + Math.floor(dayC) + ' 天前';
  37. }
  38. else if (hourC >= 1) {
  39. result = '' + Math.floor(hourC) + ' 小时前';
  40. }
  41. else if (minC >= 1) {
  42. result = '' + Math.floor(minC) + ' 分钟前';
  43. }
  44. else
  45. result = '刚刚';
  46. return result;
  47. }
  48. exports.relativeDate = relativeDate;