2015-01-03 73 views
0

我想重寫下面的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,但輸出仍然不是預期的那種。

+0

你可能需要一個.toFixed在少數地方 – mplungjan

回答

2

請參閱下面的代碼修正意見:

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; 

    // "elapsed" is in milliseconds when it was in days (Rational) in the 
    // Ruby version. Fix: 
    elapsed = elapsed/1000/3600/24; 

    tense = elapsed > 0 ? 'since' : 'until'; 
    interval = 1.0; 

    parts = intervals.map(function(item) { 
    var number; 
    interval /= item[1]; 

    // You mixed "number" with "elapsed", and calculated them in 
    // the wrong order. Fix: 
    number = Math.floor(elapsed/interval); 
    elapsed = elapsed % interval; 

    return number + " " + item[0] + (number !== 1 ? 's' : ''); 
    }); 

    return console.log(parts.join(', ') + " " + tense); 
}; 

since('Sep 27 19:01:41 2014 MST'); 
97 days, 15 hours, 33 minutes, 21 seconds since 
+0

我知道有別的東西!自我注意:Ruby的日期使用天數爲單位 –

+1

有這樣的庫。如果您正在進行排程,請查看moment.js(http://momentjs.com)和later.js(http://bunkat.github.io/later/)。 –