如何计算出两个日期之间的年份和剩余天数

How to work out the years and left over days between 2 dates

我正在尝试算出两个日期之间的年份和日期。例如 "How many years and remaining days has it been since World War 2?"。我可以计算出总天数,但我正在努力确保剩余天数是正确的。我也没有考虑闰年,因为我不知道从哪里开始。

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>

尝试使用 .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/


编辑、更新

That works but I am from the UK so i need to convert the date format once it has been stored in the variable. Is that possible?

尝试使用 String.prototype.split()Array.prototype.slice()Array.prototype.reverse()Array.prototype.join()String.prototype.concat()[ 将 input 转换为 "dd/mm/yy" 格式=26=]

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/