我正在尝试计算两个日期之间的年份和日期。一个例子是“自第二次世界大战以来多少年和剩余的几天?”。我可以计算总天数,但我正在努力确保剩余的日数是正确的。我也没有考虑到闰年,因为我不知道从哪里开始。
http://jsfiddle.net/aw5rvpk0/16/
jQuery
function parseDate(str) {
var mdy = str.split('/')
return new Date(mdy[2], mdy[0]-1, mdy[1]);
}
function daydiff(first, second) {
return (second-first)/(1000*60*60*24);
}
var totalDayCount = Math.round((daydiff(parseDate($('#first').val()), parseDate($('#second').val()))));
var yearCount = Math.round((totalDayCount / 365) * 10) / 10;
var dayCountMinusYears = Math.round((totalDayCount - (yearCount * 365)));
$('.years').text(yearCount);
$('.days').text(dayCountMinusYears);
HTML
<input id="first" value="1/1/2000"/>
<input id="second" value="6/10/2005"/>
<div>Year Count <span class="years">0</span></div>
<div>Day Count Minus The Years Count <span class="days">0</span></div>
答案 0 :(得分:1)
尝试使用.getTime()
,String.prototype.split()
,.toFixed()
var inputs = $("input");
var then = new Date(inputs.eq(0).val()).getTime();
var now = new Date(inputs.eq(1).val()).getTime();
var years = ((now - then) / 86400000 / 365).toFixed(2);
$(".years").text(years.split(".")[0]);
$(".days").text(365 * Number("." + years.split(".")[1]));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<input id="first" value="1/1/2000"/>
<input id="second" value="6/10/2005"/>
<div>Year Count <span class="years">0</span></div>
<div>Day Count Minus The Years Count <span class="days">0</span></div>
jsfiddle http://jsfiddle.net/aw5rvpk0/17/
修改,更新
虽然有效,但我来自英国,所以我需要转换日期格式 一旦它存储在变量中。这可能吗?
尝试使用input
,String.prototype.split()
,Array.prototype.slice()
,Array.prototype.reverse()
,Array.prototype.join()
<将String.prototype.concat()
转换为“dd / mm / yy”格式/ p>
var inputs = $("input");
var then = inputs.eq(0).val();
then = new Date(then.split("/").slice(0,2).reverse()
.join("/").concat("/" + then.slice(-4))).getTime();
var now = inputs.eq(1).val();
now = new Date(now.split("/").slice(0,2).reverse()
.join("/").concat("/" + now.slice(-4))).getTime();
console.log(then, now)
var years = ((now - then) / 86400000 / 365).toFixed(5);
$(".years").text(years.split(".")[0]);
$(".days").text(365 * Number("." + years.split(".")[1]));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="first" value="30/01/2000"/>
<input id="second" value="31/01/2001"/>
<div>Year Count <span class="years">0</span></div>
<div>Day Count Minus The Years Count <span class="days">0</span></div>
jsfiddle http://jsfiddle.net/aw5rvpk0/36/