common.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. export function caculateTimeago(dateTimeStamp) {
  2. const minute = 1000 * 60; // 把分,时,天,周,半个月,一个月用毫秒表示
  3. const hour = minute * 60;
  4. const day = hour * 24;
  5. const week = day * 7;
  6. const now = new Date().getTime(); // 获取当前时间毫秒
  7. const diffValue = now - dateTimeStamp; // 时间差
  8. let result = '';
  9. if (diffValue < 0) {
  10. return;
  11. }
  12. const minC = diffValue / minute; // 计算时间差的分,时,天,周,月
  13. const hourC = diffValue / hour;
  14. const dayC = diffValue / day;
  15. const weekC = diffValue / week;
  16. if (weekC >= 1 && weekC <= 4) {
  17. result = ` ${parseInt(weekC, 10)}周前`;
  18. } else if (dayC >= 1 && dayC <= 6) {
  19. result = ` ${parseInt(dayC, 10)}天前`;
  20. } else if (hourC >= 1 && hourC <= 23) {
  21. result = ` ${parseInt(hourC, 10)}小时前`;
  22. } else if (minC >= 1 && minC <= 59) {
  23. result = ` ${parseInt(minC, 10)}分钟前`;
  24. } else if (diffValue >= 0 && diffValue <= minute) {
  25. result = '刚刚';
  26. } else {
  27. const datetime = new Date();
  28. datetime.setTime(dateTimeStamp);
  29. const Nyear = datetime.getFullYear();
  30. const Nmonth = datetime.getMonth() + 1 < 10 ? `0${datetime.getMonth() + 1}` : datetime.getMonth() + 1;
  31. const Ndate = datetime.getDate() < 10 ? `0${datetime.getDate()}` : datetime.getDate();
  32. result = `${Nyear}-${Nmonth}-${Ndate}`;
  33. }
  34. return result;
  35. }
  36. export function formateTime(secondTime) {
  37. const time = secondTime;
  38. let newTime;
  39. let hour;
  40. let minite;
  41. let seconds;
  42. if (time >= 3600) {
  43. hour = parseInt(time / 3600) < 10 ? `0${parseInt(time / 3600)}` : parseInt(time / 3600);
  44. minite = parseInt(time % 60 / 60) < 10 ? `0${parseInt(time % 60 / 60)}` : parseInt(time % 60 / 60);
  45. seconds = time % 3600 < 10 ? `0${time % 3600}` : time % 3600;
  46. if (seconds > 60) {
  47. minite = parseInt(seconds / 60) < 10 ? `0${parseInt(seconds / 60)}` : parseInt(seconds / 60);
  48. seconds = seconds % 60 < 10 ? `0${seconds % 60}` : seconds % 60;
  49. }
  50. newTime = `${hour}:${minite}:${seconds}`;
  51. } else if (time >= 60 && time < 3600) {
  52. minite = parseInt(time / 60) < 10 ? `0${parseInt(time / 60)}` : parseInt(time / 60);
  53. seconds = time % 60 < 10 ? `0${time % 60}` : time % 60;
  54. newTime = `00:${minite}:${seconds}`;
  55. } else if (time < 60) {
  56. seconds = time < 10 ? `0${time}` : time;
  57. newTime = `00:00:${seconds}`;
  58. }
  59. return newTime;
  60. }