在几个月内获得差异,并在javascript中列出两个日期之间的数组中的月份

时间:2015-09-23 13:38:37

标签: javascript date

我在下面给出了两个日期,其格式是我需要获得它们之间的月数。我尝试了Difference in months between dates in Javascript: 但格式与我所拥有的格式不匹配。任何人都可以建议修复吗?

 startDate:"2015-09-07",
 endDate: "2015-12-30"

此外,我需要显示日期之间的月份,如:

var months=["sept","oct","nov","dec","jan","feb"]

1 个答案:

答案 0 :(得分:-1)

好吧,你总是可以分割字符串并像这样使用月份:

var startDate = startDate.split("-");
var endDate= endDate.split("-");
var MonthDifference = endDate[1] - startDate[1];

所以你可以做一下这个功能:

function DifferenceInMonths(startDate, endDate){
    startDate= startDate.split("-");
    endDate= endDate.split("-");
    return endDate[1] - startDate[1];
}

但是,我们面临的问题是,这些日期可能会在两年内发生。如果你试试这个怎么办:

function differenceCalculatedInMonthsByUnix(startDate, endDate){
startDate = new Date(startDate).getTime();
endDate= new Date(endDate).getTime();
var difference = endDate - startDate;
return timeMe(difference);
}

function timeMe(unix_timestamp){
    unix_timestamp = parseInt(unix_timestamp);
    var date = new Date(unix_timestamp);
    var days = date.getDate();
    var month = date.getMonth() + 1;
    var year = date.getFullYear()
    // hours part from the timestamp
    var hours = date.getHours();
    // minutes part from the timestamp
    var minutes = "0" + date.getMinutes();
    // seconds part from the timestamp
    var seconds = "0" + date.getSeconds();
    // will display time in 10:30:23 format
    var formattedTime = days + '.' + month + '.' + year + ' at:' + hours + ':' + minutes.substr(minutes.length-2) + ':' + seconds.substr(seconds.length-2);
    return (12 * year) + month
}

我不确定我是自己做的TimeMe()还是我从stackOverflow找到它所以如果有人需要积分,请告诉我。 但是,这个想法是,我们将日期转换为unix时间戳,计算差异,并将其变为几个月。