util.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. function friendlyDate(timestamp) {
  2. var formats = {
  3. 'year': '%n% 年前',
  4. 'month': '%n% 月前',
  5. 'day': '%n% 天前',
  6. 'hour': '%n% 小时前',
  7. 'minute': '%n% 分钟前',
  8. 'second': '%n% 秒前',
  9. };
  10. var now = Date.now();
  11. var seconds = Math.floor((now - timestamp) / 1000);
  12. var minutes = Math.floor(seconds / 60);
  13. var hours = Math.floor(minutes / 60);
  14. var days = Math.floor(hours / 24);
  15. var months = Math.floor(days / 30);
  16. var years = Math.floor(months / 12);
  17. var diffType = '';
  18. var diffValue = 0;
  19. if (years > 0) {
  20. diffType = 'year';
  21. diffValue = years;
  22. } else {
  23. if (months > 0) {
  24. diffType = 'month';
  25. diffValue = months;
  26. } else {
  27. if (days > 0) {
  28. diffType = 'day';
  29. diffValue = days;
  30. } else {
  31. if (hours > 0) {
  32. diffType = 'hour';
  33. diffValue = hours;
  34. } else {
  35. if (minutes > 0) {
  36. diffType = 'minute';
  37. diffValue = minutes;
  38. } else {
  39. diffType = 'second';
  40. diffValue = seconds === 0 ? (seconds = 1) : seconds;
  41. }
  42. }
  43. }
  44. }
  45. }
  46. return formats[diffType].replace('%n%', diffValue);
  47. }
  48. export {
  49. friendlyDate
  50. }