js根据时间转化成刚刚,多少分钟前,多少小时前,一年内,超过一年

76 阅读1分钟
import moment from 'moment';
const computedTime = (TimeStr) => {
 // 使用moment函数来尝试解析时间字符串
 const parsedDate = moment(TimeStr);
 // 验证是否为时间字符串
 if (!parsedDate.isValid()) return TimeStr;
 // 获取当前时间
 const currentTime = moment();
 // 计算时间差(以毫秒为单位)
 const timeDifferenceInMilliseconds = currentTime.diff(parsedDate);
 // 将毫秒转换为分钟
 const timeDifferenceInMinutes = moment.duration(timeDifferenceInMilliseconds).asMinutes();
 const timeDifferenceInHours = moment.duration(timeDifferenceInMilliseconds).asHours();
 const timeDifferenceInDays = moment.duration(timeDifferenceInMilliseconds).asDays();
 if (Math.abs(timeDifferenceInMinutes) < 1) { // 判断时间差是否小于1分钟,并根据结果进行相应处理
  return '刚刚';
 } else if (Math.abs(timeDifferenceInMinutes) < 60) {
  // 如果时间差在一个小时内,返回N分钟前
  return `${Math.abs(Math.round(timeDifferenceInMinutes))}分钟前`;
 } else if (Math.abs(timeDifferenceInHours) < 24) {
  // 如果时间差在24小时内,返回N小时前
  return `${Math.abs(Math.round(timeDifferenceInHours))}小时前`;
 } else if (Math.abs(timeDifferenceInDays) < 365) {
  // 如果时间差在同一年内且超过24小时,格式化为MM-DD hh:mm:ss
  return parsedDate.format('MM-DD HH:mm:ss');
 }
 // 如果时间差跨越多年,将时间转为YYYY-MM-DD hh:mm:ss
 return parsedDate.format('YYYY-MM-DD HH:mm:ss');
};