我现在有一份年份清单,今年我得到了两者之间的差异,这里一切都很好但是现在我想要更加精确并添加几个月而且我不太想到这样做的一种方式。
这是我到目前为止所拥有的:
HTML
<ul>
<li>1989</li>
<li>1991</li>
<li>2004</li>
</ul>
JS
var custom = [
' years old', ' years of experience', ' years of learning'];
var i = 0;
$('ul li').each(function () {
var d = new Date();
var y = (d.getFullYear());
var year = $(this).html();
var diff = (y - year);
$(this).html(diff + custom[i]);
i = (i + 1) % custom.length;
});
我想更改我的列表[添加月份]:
<ul>
<li>8/1989</li>
<li>10/1991</li>
<li>4/2004</li>
</ul>
..我想把它输出:
答案 0 :(得分:0)
您可以通过一点分割和模数得到粗略估算值。
var startDate = new Date("1995").getTime()/1000;
var endDate = new Date("june 1999").getTime()/1000;
var diff = endDate - startDate;
var totalYears = Math.floor(diff/365);
var totalMonths = Math.floor(diff/30);
var y = totalYears;
var m = totalMonths % 12;
console.log('time: ' + y + ' year(s) and ' + m + ' month(s)');
输出:time: 4 year(s) and 5 month(s)
答案 1 :(得分:0)
Here你有一个工作小提琴
JS:
$('ul li').each(function () {
// Get the current date of the loop (mm/yyyy) and split it
var current = $(this).html().split('/');
var year = current[1]; // Get the year
var month = current[0] // Get the month
// Get the current real time
var d = new Date();
var y = (d.getFullYear());
var m = (d.getMonth() + 1); // Add one to the month, because .getMonth() is zero indexed
var yDiff = (y - year);
var mDiff = (m - month);
// Now, if the month difference is negative, add 12 months to it and substract 1 year.
if (mDiff < 0) {
mDiff = mDiff + 12;
yDiff--;
}
$(this).html(mDiff + ' month(s) and ' + yDiff + custom[i]);
i = (i + 1) % custom.length;
//Thats it!
});