datetime.js 1.2 KB

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