如何计算两个日期的天数

我想计算两个日期的天数我的日期格式是dd-mmm-yyyy这样的"10-Nov-2020" 有人可以帮我吗?


<script>

        var deFromDate;

        var deToDate;

        var statarr;

        function deFromDateChanged(s, e) {

            deFromDate = (s.GetInputElement().value)

            //statarr = deFromDate.split('-');

        }

        function deToDateChanged(s, e) {

            deToDate = (s.GetInputElement().value)

            var Difference_In_Time = deToDate.getTime() - deFromDate.getTime();

            var Difference_In_Days = Difference_In_Time / (1000 * 3600 * 24);

            alert(Difference_In_Days);

        }


    </script>

我收到错误getTime()是否有其他方法可以执行相同操作


守候你守候我
浏览 177回答 2
2回答

三国纷争

使用Date.parse()(尽管由于实现不一致而不鼓励使用)function datediff(first, second) {    return Math.round((second-first)/(1000*60*60*24));}const deFromDate = Date.parse('10-Nov-2020');const deToDate = Date.parse('15-Nov-2020');console.log(datediff(deFromDate, deToDate));手动解析var months = {    'Jan' : 1,    'Feb' : 2,    'Mar' : 3,    'Apr' : 4,    'May' : 5,    'Jun' : 6,    'Jul' : 7,    'Aug' : 8,    'Sep' : 9,    'Oct' : 10,    'Nov' : 11,    'Dec' : 12}function parseDate(str) {    var [dd, mmm, yyyy] = str.split('-');    return new Date(yyyy, months[mmm]-1, dd); // months are 0 indexed}function datediff(first, second) {    return Math.round((second-first)/(1000*60*60*24));}const deFromDate = parseDate('10-Nov-2020');const deToDate = parseDate('15-Nov-2020');console.log(datediff(deFromDate, deToDate));

aluckdog

我尝试使用正则表达式:&nbsp;<script>&nbsp; &nbsp; &nbsp; &nbsp; var deFromDate;&nbsp; &nbsp; &nbsp; &nbsp; var deToDate;&nbsp; &nbsp; &nbsp; &nbsp; var dt1;&nbsp; &nbsp; &nbsp; &nbsp; var dt2;&nbsp; &nbsp; &nbsp; &nbsp; function deFromDateChanged(s, e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; deFromDate = (s.GetInputElement().value)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; dt1 = new Date(deFromDate.replace(/(\d{2})-(\d{2})-(\d{4})/, "$2/$1/$3"));&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; function deToDateChanged(s, e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; deToDate = (s.GetInputElement().value)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; dt2 = new Date(deToDate.replace(/(\d{2})-(\d{2})-(\d{4})/, "$2/$1/$3"));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var result = ((dt2 - dt1) / 86400000);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; alert(result);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; </script>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript