yyyy-mm-dd格式两天之间的差异(以天为单位)?

时间:2016-03-14 12:13:28

标签: javascript date datetime

很抱歉,如果之前有人询问,但我找不到任何内容。这基本上就是我要做的事情:

new Date(response.departureDate).getTime() - new Date(response.arrivalDate).getTime()

我需要计算到达和离开日期之间的总天数(总是整数)。这些日期是字符串,结构为'YYYY-MM-DD'

我该怎么做?

5 个答案:

答案 0 :(得分:1)

看看迈尔斯'回答here 只需将其更改为:

function parseDate(str) {
var mdy = str.split('-')
return new Date(mdy[2], mdy[0]-1, mdy[1]);
}

function daydiff(first, second) {
    return Math.round((second-first)/(1000*60*60*24));
}

并使用:

daydiff(parseDate(response.departureDate), parseDate(response.arrivalDate));

答案 1 :(得分:0)

您可以使用RegEx进行更改。

new Date(response.departureDate.replace(/-/g, "/")).getTime()
    - new Date(response.arrivalDate.replace(/-/g, "/")).getTime()

因此,RegEx .replace(/-/g, "/")会将所有-替换为/,JavaScript将能够正确阅读。

答案 2 :(得分:0)

你可以使用regexp或更多更简单的方法来熟悉 function fixNum(str, newnum) { return str.replace(/\[\d+\]/,'[' + newnum + ']') } API,它可以让你非常顺利地处理JS中的日期(在Node和浏览器中工作)

http://momentjs.com/

它确实为您的工具箱添加了另一个工具,但是只要您操作日期,它就是值得的恕我直言。

与MomentJS合作的方式:

MomentJS

答案 3 :(得分:0)

我希望此示例能为您提供帮助

除了.diff()之外,您还可以使用片刻持续时间:http://momentjs.com/docs/#/durations/

示例小提琴https://jsfiddle.net/abhitalks/md4jte5d/

示例代码段

$("#btn").on('click', function(e) {
    var fromDate = $('#fromDate').val(), 
        toDate = $('#toDate').val(), 
        from, to, druation;

    from = moment(fromDate, 'YYYY-MM-DD'); // format in which you have the date
    to = moment(toDate, 'YYYY-MM-DD');     // format in which you have the date

    /* using duration */
    duration = moment.duration(to.diff(from)).days(); // you may use duration

    /* using diff */
    //duration = to.diff(from, 'days')     // alternatively you may use diff

    /* show the result */
    $('#result').text(duration + ' days');

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.11.1/moment.min.js"></script>
From: <input id="fromDate" type='date' />
To: <input id="toDate" type='date' />&nbsp;&nbsp;
<button id="btn">Submit</button><hr />
<p id="result"></p>

答案 4 :(得分:0)

你可以使用这样的东西

function countDays(date1, date2)
{
    var one_day=1000*60*60*24;
    return Math.ceil((date1.getTime()- date2.getTime()) /one_day);
}

countDays(new Date(response.departureDate), new Date(response.arrivalDate));
相关问题