Created
July 12, 2019 14:18
-
-
Save redblue9771/ba0c0bdc3d8ac364284992893f147dc8 to your computer and use it in GitHub Desktop.
JavaScript 中一些时间功能的实现 - 给一个时间戳,返回距离现在多久了
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 给一个时间戳,返回距离现在多久了 | |
* @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