0

我只需要选择日、月和年(分别),然后计算到期日。为什么这不能正常工作?我使用substr正确吗?

http://jsfiddle.net/infatti/XeqPT/15/

function daysUntil(year, month, day) {
  var now = new Date(),
      dateEnd = new Date(year, month - 1, day), // months are zero-based
      days = (dateEnd - now) / 1000/60/60/24;   // convert milliseconds to days

  return Math.round(days);
}

$('#paging1 ul li').each(function () {

    var monthDue = $(this).find('.due-date').text().substr(0,2);
    var dayDue = $(this).find('.due-date').text().substr(3,2);
    var yearDue = $(this).find('.due-date').text().substr(6,4);

    $(this).find('.days-due').text(daysUntil(yearDue, monthDue, dayDue));

});
4

3 回答 3

0

你可以试试这个:

var monthDue = $('.due-date').text().substr(0,2);
var dayDue = $('.due-date').text().substr(3,2);
var yearDue = $('.due-date').text().substr(6,4);

我还建议您查看 moment.js 进行日期操作或计算。 http://momentjs.com/docs/#/displaying/difference/

于 2013-05-06T22:14:06.240 回答
0

$(this)不是你想的那样,也没有找到.due-date元素,试试这个方法:

/* caching the relevant text to avoid having to find the same element/text
   multiple times: */
var due = $('.due-date').text(),
    monthDue = due.substr(0,2),
    dayDue = due.substr(3,2),
    yearDue = due.substr(6,4);

// to demonstrate that you're getting the relevant text
console.log(yearDue, monthDue, dayDue);

$('.days-due').each(function(){
    $(this).text(daysUntil(yearDue, monthDue, dayDue));
});

JS 小提琴演示

于 2013-05-06T22:14:51.960 回答
0

LIVE DEMO

function daysUntil(untilDate) {
    var Time = new Date(untilDate).getTime();
    var currTime = new Date().getTime();
    var difference = Time-currTime; 
    return Math.ceil( difference/(1000*60*60*24) );   
}


$('.days-due').each(function() {
    var dateUntil = $('.due-date').text(); // use something more specific
    $(this).text( daysUntil( dateUntil ) );
} );
于 2013-05-06T22:23:05.143 回答