2010年1月12日 星期二

[引用]漂亮的時間格式 (pretty date)

來源:http://jsmore.com/archives/recursive-pretty-date/


var niceTime = (function() {:

var ints = {
second: 1,
minute: 60,
hour: 3600,
day: 86400,
week: 604800,
month: 2592000,
year: 31536000
};

return function(time) {

time = +new Date(time);

var gap = ((+new Date()) - time) / 1000,
amount, measure;

for (var i in ints) {
if (gap > ints[i]) { measure = i; }
}

amount = gap / ints[measure];
amount = gap > ints.day ? (Math.round(amount * 100) / 100) : Math.round(amount);
amount += ' ' + measure + (amount > 1 ? 's' : '') + ' ago';

return amount;
};

})();


Usage:

niceTime( 1 ); // => "39.57 years ago"
niceTime( "Sun Mar 01 20:20:02 +0000 2009" ); // => "4.65 months ago"
niceTime( "July 19, 2009 12:06:00" ); // => "26 seconds ago"


然後我決定寫得更深入點,創建一個遞歸的版本,直到匹配到可用的最小的時間單位:


var prettyTimeDiff = (function() {

var ints = {
second: 1,
minute: 60,
hour: 3600,
day: 86400,
week: 604800,
month: 2628000,
year: 31536000,
decade: 315360000
};

return function(aTime, bTime) {

aTime = +new Date(aTime);
bTime = bTime === undefined ? +new Date() : +new Date(bTime);

var timeGap = Math.abs(bTime - aTime) / 1000,
amount, measure, remainder, smallest;

for (var i in ints) {
if (timeGap > ints[i]) {
measure = i;
}
if (!smallest || ints[i] < smallest) { smallest = ints[i]; } } amount = Math.floor(timeGap / ints[measure]); if (timeGap > 31536000) {
/* Handle leap years */
timeGap -= Math.floor(ints[measure] * amount / 31536000 / 4) * 86400;
}

amount += ' ' + measure + (amount > 1 ? 's' : '');

remainder = timeGap % ints[measure];

if (remainder >= smallest) {
amount += ', ' + arguments.callee( +new Date() - remainder*1000 );
}

return amount;
};

})();


我決定叫它 prettyTimeDiff,因為它可以比較任意兩個時間的差值,並返回一個漂亮的格式。如果參數隻傳一個時間的話,則認為是計算它與當前時間的差值。

Usage:

prettyTimeDiff( 0 );
// => "3 decades, 9 years, 6 months, 2 weeks, 4 days, 51 minutes, 25 seconds"

prettyTimeDiff( "July 1, 2005", "July 2, 2006" );
// => "1 year, 24 hours"

prettyTimeDiff( 0, 5000 );
// => "5 seconds"

prettyTimeDiff( "Sun Mar 01 20:20:02 +0000 2009" ) + ' ago';
// => "4 months, 2 weeks, 4 days, 37 minutes, 49 seconds ago"

你可以通過配置的方法決定哪些時間單位需要使用;比如,如果你不需要十年(decade),只需要刪除 ints['decade']。如果只需要單位 分(minute)、年(year)和十年(decade),只需簡單 註釋/刪除 其他的單位就可以了:

var ints = {
//second: 1,
minute: 60,
//hour: 3600,
//day: 86400,
//week: 604800,
//month: 2628000,
year: 31536000,
decade: 315360000
};

上面調整後的顯示結果

prettyTimeDiff( "January 19, 1988" )
// => "2 decades, 1 year, 262873 minutes"

這個可以很方便的使用在其它程序裡。

【下列文章您可能也有興趣】

沒有留言: