gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 09:18:57 25 4
gpt4 key购买 nike

我正在尝试计算两个日期之间的年数和天数。一个例子是“自第二次世界大战以来已经过去了多少年和剩余天数?”。我可以算出总天数,但我很难确保剩余天数正确。我也没有考虑闰年,因为我不知道从哪里开始。

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() 将 input 转换为“dd/mm/yy”格式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/

关于javascript - 如何计算两个日期之间的年份和剩余天数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31896216/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com