为什么我的约会是无效日期

时间:2013-11-20 13:02:45

标签: javascript jquery date object nan

我试图计算JavaScript中两个日期对象之间的日期差异。但是,当我尝试使用Math.round函数时,我得到NaN

此问题出现在此行

var deliveryDays = Math.round(Math.abs((currentDate.getTime() - basketDate.getTime())/(oneDay)));

请参阅以下代码:

 function datePicker() {
     $('#datePicker').datepicker();

     $('.ui-datepicker').addClass('datePicker'); //This is added to the class ui-datepicker which is generated when the date picker is generated.
     var currentDate = $.datepicker.formatDate('dd-mm-yy', new Date()); // Get today's date.
     currentDate = new Date(currentDate); // Convert string to date (string must be an appropriate format.

     $("#datePickerConfirmation").click(function () {
         var basketDate = $('#datePicker').datepicker('getDate');
         basketDate = $.datepicker.formatDate('dd-mm-yy', new Date(basketDate)); // Changes the date format to dd-mm-yyyy.
         basketDate = new Date(basketDate);

         // This block works out the difference between the current date and the selected date.
         var oneDay = 24 * 60 * 60 * 1000;
         var deliveryDays = Math.round(Math.abs((currentDate.getTime() - basketDate.getTime()) / (oneDay)));

         basketDate = basketDate.toString();
         currentDate = currentDate.toString();
         deliveryDays = deliveryDays;

         var result = window.confirm('Confirm Date: ' + basketDate + '\n \nDays to Delivery: ' + deliveryDays);
         if (result == true) {
             console.log("User pressed Ok / Confirm   Date set to: " + basketDate);
             // Do nothing
         } else {
             console.log("User pressed Cancel, basket set to null");
             basketDate = null;
             console.log(basketDate);
         }
     });
 }

1 个答案:

答案 0 :(得分:0)

您无需将日期转换为字符串,然后再转换为日期。替换这些行

var currentDate = $.datepicker.formatDate('dd-mm-yy', new Date()); // Get today's date.
currentDate = new Date(currentDate);

用这个

var currentDate = new Date();

以及这些行

basketDate = $.datepicker.formatDate('dd-mm-yy', new Date(basketDate)); // Changes the date format to dd-mm-yyyy.
basketDate = new Date(basketDate);

用这个

basketDate = new Date(basketDate);