datetime.js 1.2 KB

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