2014-10-11 140 views
-1

好吧,我在這裏發現了很多像這樣的問題,試圖獲得年,月和日的兩個日期之間的差異......但沒有完成我的答案需求。在JavaScript中使用年,月,日兩個日期獲取差異

所以我寫了一些東西來計算,它似乎工作,但也許一些專家在這裏可以做出更正或幫助使這更簡單。

+0

您應該使用UTC時間/紀元時間 - 從較大的日期減去較短的日期,然後將UTC結果轉換回「正常」格式。這是最優雅的方式這個 – 2014-10-11 05:40:44

+0

moment.js或date.js應該處理您的所有需求 – mplungjan 2014-10-11 05:44:07

+0

我寫了一個函數在這裏。這滿足了我的要求,我只是發佈這個讓解決方案,可以幫助一些尋找這個。謝謝,moment.js不處理這個問題。 date.js我沒試過。 – xploshioOn 2014-10-11 05:47:21

回答

2

所以這是我的功能,這接收兩個日期,做所有的工作,並返回一個json與3個值,年,月和日。

var DifFechas = {}; 

// difference in years, months, and days between 2 dates 
DifFechas.AMD = function(dIni, dFin) { 
    var dAux, nAnos, nMeses, nDias, cRetorno 
    // final date always greater than the initial 
    if (dIni > dFin) { 
     dAux = dIni 
     dIni = dFin 
     dFin = dAux 
    } 
    // calculate years 
    nAnos = dFin.getFullYear() - dIni.getFullYear() 
    // translate the initial date to the same year that the final 
    dAux = new Date(dIni.getFullYear() + nAnos, dIni.getMonth(), dIni.getDate()) 
    // Check if we have to take a year off because it is not full 
    if (dAux > dFin) { 
     --nAnos 
    } 
    // calculate months 
    nMeses = dFin.getMonth() - dIni.getMonth() 
    // We add in months the part of the incomplete Year 
    if (nMeses < 0) { 
     nMeses = nMeses + 12 
     } 
    // Calculate days 
    nDias = dFin.getDate() - dIni.getDate() 
    // We add in days the part of the incomplete month 
    if (nDias < 0) { 
     nDias = nDias + this.DiasDelMes(dIni) 
    } 
    // if the day is greater, we quit the month 
    if (dFin.getDate() < dIni.getDate()) { 
     if (nMeses == 0) { 
      nMeses = 11 
     } 
     else { 
      --nMeses 
     } 
    } 
    cRetorno = {"años":nAnos,"meses":nMeses,"dias":nDias} 
    return cRetorno 
} 

DifFechas.DiasDelMes = function (date) { 
    date = new Date(date); 
    return 32 - new Date(date.getFullYear(), date.getMonth(), 32).getDate(); 
} 

希望這可以幫助尋找解決方案的人。

這是一個新版本的其他人一樣,似乎也沒有誤差修改,希望這個作品更好

+0

這行有錯誤var mesant = dayssInmonths(until.setmonths(until.getMonth() - 1));' – 2015-06-16 05:40:49

+0

將此轉換爲'until.setmonths'到這個'until.setMonth' – 2015-06-16 05:41:22

+0

完成@AnikIslamAbhi – xploshioOn 2015-06-16 17:30:12

5

您可以使用moment.js簡化此:

function difference(d1, d2) { 
    var m = moment(d1); 
    var years = m.diff(d2, 'years'); 
    m.add(-years, 'years'); 
    var months = m.diff(d2, 'months'); 
    m.add(-months, 'months'); 
    var days = m.diff(d2, 'days'); 

    return {years: years, months: months, days: days}; 
} 

例如,

> difference(Date.parse("2014/01/20"), Date.parse("2012/08/17")) 
Object {years: 1, months: 5, days: 3} 

如果這就是你真正想要的,moment.js還可以返回人類可讀的差異(「在一年中」)。

+0

我不想使用完整的庫或插件,如果我只是需要一個功能。 – xploshioOn 2014-10-11 06:28:45