Reputation: 5986
I am trying to work out the years and days between 2 dates. An example would be "How many years and remaining days has it been since World War 2?". I can work out the total days but i am struggling to make sure the remaining day count is correct. I am also not taking into account leap years as I don't know where to start with that.
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>
Upvotes: 0
Views: 66
Reputation: 1
Try utilizing .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/
Edit, Updated
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?
Try converting input
to "dd/mm/yy" format utilizing String.prototype.split()
, Array.prototype.slice()
, Array.prototype.reverse()
, Array.prototype.join()
, String.prototype.concat()
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/
Upvotes: 1