我想计算从html(输入类型日期值)获得的两个日期之间的时间范围。
我想获取年,月和日的时间表。
即:2017-01-01和2019-02-15
2年, 1个月, 14天
谢谢
答案 0 :(得分:1)
您可以使用时刻库
var url = "https://www.abc.example.it/wp-json/wp/v2/posts?per_page=50&status=publish";
var subdomain = (new URL(url)).hostname.split('.')[1];
var domain = (new URL(url)).hostname.split('.')[2];
console.log(subdomain, domain)
或
var a = moment([2017, 1, 1]);
var b = moment([2019, 2,15]);
b.diff(a, 'days') //get difference in days..
b.diff(a, 'months') //get difference in months.
b.diff(a, 'years') //get difference in years..
您可以在此处找到该库。Moment.js library
我希望这会有所帮助。
答案 1 :(得分:1)
您可以使用此功能。
<script>
function getDateDifference(startDate, endDate) {
if (startDate > endDate) {
console.error('Start date must be before end date');
return null;
}
var startYear = startDate.getFullYear();
var startMonth = startDate.getMonth();
var startDay = startDate.getDate();
var endYear = endDate.getFullYear();
var endMonth = endDate.getMonth();
var endDay = endDate.getDate();
var february = (endYear % 4 == 0 && endYear % 100 != 0) || endYear % 400 == 0 ? 29 : 28;
var daysOfMonth = [31, february, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
var startDateNotPassedInEndYear = (endMonth < startMonth) || endMonth == startMonth && endDay < startDay;
var years = endYear - startYear - (startDateNotPassedInEndYear ? 1 : 0);
var months = (12 + endMonth - startMonth - (endDay < startDay ? 1 : 0)) % 12;
var days = startDay <= endDay ? endDay - startDay : daysOfMonth[(12 + endMonth - 1) % 12] - startDay + endDay;
return {
years: years,
months: months,
days: days
};
}
var result = getDateDifference(new Date("2018-01-01"), new Date("2019-01-02"));
//Print in console array with value
console.log(result);
var text = result.years+" year, "+result.months+" month, "+result.days+" days";
alert(text);
</script>
使用getDateDifference
和参数第一个日期和第二个日期。在警报中,我插入演示打印。
答案 2 :(得分:1)
function getTimeBetweenDates(e) {
var date1 = new Date(document.getElementById("date1").value);
var date2 = new Date(document.getElementById("date2").value);
var diff;
if (date1 < date2) {
diff = new Date(date2 - date1);
} else {
diff = new Date(date1 - date2);
}
var years = (diff.getFullYear() - 1970);
var months = diff.getMonth();
var days = diff.getDate();
var yearTxt = "year";
var monthTxt = "month";
var dayTxt = "day";
if (years > 1) yearTxt += "s";
if (months > 1) monthTxt += "s";
if (days > 1) dayTxt += "s";
if (years >= 0) {
document.getElementById("showdiff").innerHTML = years + " " + yearTxt + ", " + months + " " + monthTxt + ", " + days + " " + dayTxt;
} else {
document.getElementById("showdiff").innerHTML = "Equal dates";
}
}
<form id="form1" action="" method="" onSubmit="event.preventDefault(); getTimeBetweenDates();">
<input type="date" id="date1">
<input type="date" id="date2">
</form>
<br>
<button type="submit" form="form1" value="Send">Send</button>
<br>
<p id="showdiff"></p>