博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
/**
* 获取距离当前时间的时间长度
* @param {Number} timestamp     - 要转换的时间参数(单位为秒)
* @returns {String}
*/
function simplyToRelativeTime(timestamp) {
  let currentUnixTime = Math.round((new Date()).getTime() / 1000);       // 当前时间的秒数
  let deltaSecond = currentUnixTime - parseInt(timestamp, 10);            // 当前时间与要转换的时间差( s )
  let result;
 
  if (deltaSecond < 60) {
    result = deltaSecond + '秒前';
  } else if (deltaSecond < 3600) {
    result = Math.floor(deltaSecond / 60) + '分钟前';
  } else if (deltaSecond < 86400) {
    result = Math.floor(deltaSecond / 3600) + '小时前';
  } else {
    result = Math.floor(deltaSecond / 86400) + '天前';
  }
  return result;
}