You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

timeFrom.js 1.6 KiB

3 jaren geleden
12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import timeFormat from '../../libs/function/timeFormat.js';
  2. /**
  3. * 时间戳转为多久之前
  4. * @param String timestamp 时间戳
  5. * @param String | Boolean format 如果为时间格式字符串,超出一定时间范围,返回固定的时间格式;
  6. * 如果为布尔值false,无论什么时间,都返回多久以前的格式
  7. */
  8. function timeFrom(timestamp = null, format = 'yyyy-mm-dd') {
  9. if (timestamp == null) timestamp = Number(new Date());
  10. timestamp = parseInt(timestamp);
  11. // 判断用户输入的时间戳是秒还是毫秒,一般前端js获取的时间戳是毫秒(13位),后端传过来的为秒(10位)
  12. if (timestamp.toString().length == 10) timestamp *= 1000;
  13. var timer = (new Date()).getTime() - timestamp;
  14. timer = parseInt(timer / 1000);
  15. // 如果小于5分钟,则返回"刚刚",其他以此类推
  16. let tips = '';
  17. switch (true) {
  18. case timer < 300:
  19. tips = '刚刚';
  20. break;
  21. case timer >= 300 && timer < 3600:
  22. tips = parseInt(timer / 60) + '分钟前';
  23. break;
  24. case timer >= 3600 && timer < 86400:
  25. tips = parseInt(timer / 3600) + '小时前';
  26. break;
  27. case timer >= 86400 && timer < 2592000:
  28. tips = parseInt(timer / 86400) + '天前';
  29. break;
  30. default:
  31. // 如果format为false,则无论什么时间戳,都显示xx之前
  32. if(format === false) {
  33. if(timer >= 2592000 && timer < 365 * 86400) {
  34. tips = parseInt(timer / (86400 * 30)) + '个月前';
  35. } else {
  36. tips = parseInt(timer / (86400 * 365)) + '年前';
  37. }
  38. } else {
  39. tips = timeFormat(timestamp, format);
  40. }
  41. }
  42. return tips;
  43. }
  44. export default timeFrom;