Skip to content

Instantly share code, notes, and snippets.

@redblue9771
Created July 12, 2019 14:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save redblue9771/ba0c0bdc3d8ac364284992893f147dc8 to your computer and use it in GitHub Desktop.
Save redblue9771/ba0c0bdc3d8ac364284992893f147dc8 to your computer and use it in GitHub Desktop.
JavaScript 中一些时间功能的实现 - 给一个时间戳,返回距离现在多久了
/**
* 给一个时间戳,返回距离现在多久了
* @param time 一个时间戳
* @returns {*} 时间差
*/
function returnTime(time) {
if (isNaN(time) === true)
return "Error!" + '"' + time + '"' + " is NaN";
if (time < 0) return "Error! 过去的时间大于现在的时间!";
else {
var diffValue = (Date.now() - time) / 1000 / 60;
if (diffValue < 1) return "刚刚";
if (diffValue < 60) return parseInt(diffValue) + "分钟前";
if (diffValue < 60 * 24) return parseInt(diffValue / 60) + "小时前";
if (diffValue < 60 * 24 * 30) return parseInt(diffValue / 60 / 24) + "天前";
return parseInt(diffValue / 60 / 24 / 30) + "月前";
}
}
document.write(returnTime(1509019200000));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment