我只需要选择日,月和年(单独),然后计算到期日。为什么这不正常?我正确使用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));
});
答案 0 :(得分: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/
答案 1 :(得分:0)
$(this)
不是您认为的那样wasn't finding the .due-date
element,尝试这种方法:
/* 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));
});
答案 2 :(得分: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 ) );
} );