我想重寫下面的JavaScript代碼片段,但輸出結果並不是我期待的。Ruby to Javascript =>日期計算頭痛
這是原來的Ruby代碼:「X天,X小時,X秒,因爲那一刻」
require 'date'
moment = DateTime.new(2014, 9, 27, 0, 0, 0, DateTime.now.offset)
intervals = [['day', 1], ['hour', 24], ['minute', 60], ['second', 60]]
elapsed = DateTime.now - moment
tense = elapsed > 0 ? 'since' : 'until'
interval = 1.0
parts = intervals.collect do |name, new_interval|
interval /= new_interval
number, elapsed = elapsed.abs.divmod(interval)
"#{number.to_i} #{name}#{'s' unless number == 1}"
end
puts "#{parts.join(', ')} #{tense} that moment."
這將輸出的東西沿着線
當前的JavaScript代碼,我擁有的是:
// Input: Nov 18 19:01:41 2014 MST
var since = function(date) {
var elapsed, interval, intervals, parts, tense;
date = Date.parse(date);
intervals = [['day', 1], ['hour', 24], ['minute', 60], ['second', 60]];
elapsed = (new Date).getTime() - date;
tense = elapsed > 0 ? 'since' : 'until';
interval = 1.0;
parts = intervals.map(function(item) {
var number;
interval /= item[1];
number = elapsed % interval;
elapsed = Math.floor(elapsed/interval);
return number + " " + item[0] + (number !== 1 ? 's' : void 0);
});
return console.log(parts.join(', ') + " " + tense);
};
然而,這不是預期的輸出,讓我完全沒有意義的東西:
0 days, 2.187114859220074e-7 hours, 0.000011154285782022377 minutes, 0.0000022063280195997896 seconds since that moment.
我試着做elapsed /= 1000
,但輸出仍然不是預期的那種。
你可能需要一個.toFixed在少數地方 – mplungjan