好吧,如果您不太担心准确性,那很容易。平凡的方法有什么问题?
function timeDifference(current, previous) { var msPerMinute = 60 * 1000; var msPerHour = msPerMinute * 60; var msPerDay = msPerHour * 24; var msPerMonth = msPerDay * 30; var msPerYear = msPerDay * 365; var elapsed = current - previous; if (elapsed < msPerMinute) { return Math.round(elapsed/1000) + ' seconds ago'; } else if (elapsed < msPerHour) { return Math.round(elapsed/msPerMinute) + ' minutes ago'; } else if (elapsed < msPerDay ) { return Math.round(elapsed/msPerHour ) + ' hours ago'; } else if (elapsed < msPerMonth) { return 'approximately ' + Math.round(elapsed/msPerDay) + ' days ago'; } else if (elapsed < msPerYear) { return 'approximately ' + Math.round(elapsed/msPerMonth) + ' months ago'; } else { return 'approximately ' + Math.round(elapsed/msPerYear ) + ' years ago'; }}
如果这会让您感到困扰
1 day,
1 days则可能需要对其进行调整以更好地处理奇异值(例如而不是)。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)