基本上我必须知道有多少人在几个月,几年和几天。我已经计算了几天而不是几个月,因为有闰年和几个月的长度不同。
//Variables
var now = new Date();
var totalDays = '';
var totalMonths = '';
var totalWeeks;
var birthDate = new Date(document.getElementById('selYear').value, document.getElementById('selMonth').value, document.getElementById('selDay').value);
var output = '';
//Total Days Old
var totalDays = Math.floor((now - birthDate) / 86400000);
//Total Weeks Old
totalWeeks = totalDays / 7;
totalWeeks = Math.round(totalWeeks);
//Total Months Old
totalMonths = totalDays / 30;
//Total Years
var totalYears = document.getElementById('selYear').value - now.getFullYear();
totalYears = Math.abs(totalYears);
//Outputs
output += 'You are ' + totalDays + ' days old';
output += '<br />You are ' + totalWeeks + ' weeks old';
output += '<br />You are ' + totalMonths + ' months old';
output += '<br />You are ' + totalYears + ' Years old';
我有一个应用程序要求用户提供日,月和年。我已经测试了我当前的代码( totalMonths = totalDays / 30 ),它将接近 totalMonths 它假设是(我已经检查过一个在线网站)并且日期[1/1/1990]将获取302,而它应该获取 297个月
答案 0 :(得分:0)
这对你有帮助吗?
var d = new Date();
var n = d.getMonth() + 1;
var month = totalYears * 12 + n;
alert(month);
只需在年后插入即可,它应该可以正常工作。
答案 1 :(得分:0)
我建议查看Moment.js库。它使日期愚蠢的简单。
示例:强>
var me = moment("1983-11-19");
var today = moment();
me.diff(today, "days"); // -11296
me.diff(today, "months"); // -371
me.diff(today, "years"); // -30