我试图解决这个问题已经有一段时间了,但没有成功,我在这里找到了几个类似的答案,但格式才是这里最重要的。我需要返回X年,X月,X天。
你能帮我看看,我做错了什么吗?天数不太正确。
这是一个bin
function inBetweenDays(y,m,d){
var user_date = new Date(y,m + 1,d);
var today_date = new Date();
var diff_date = (user_date - today_date);
var num_years = diff_date/31536000000;
var num_months = (diff_date % 31536000000)/2628000000;
var num_days = ((diff_date % 31536000000) % 2628000000)/86400000;
var years = Math.floor(Math.abs(num_years));
var months = Math.floor(Math.abs(num_months));
var days = Math.floor(Math.abs(num_days));
if (years >= 1) {
console.log(years + " years " + months + " months " + days + " days");
} else if (years <= 0 && months >= 0){
console.log(months + " months " + days + " days");
} else {
console.log(days + " days ");
}
}
inBetweenDays(2015,03,04);
inBetweenDays(2016,03,04);
inBetweenDays(2016,02,04);
inBetweenDays(2018,02,04);
发布于 2016-02-05 12:31:11
根据年、月、日计算两个日期之间的日历日期差的算法如下:
这可能已经在一系列重复问题中的一个现有答案中实现了,但尝试在没有算法文档的情况下发现它。借用天数的计算方法如下:
function monthDays(y, m) // full year and month in range 1-12
{ var leap = 0;
if( m == 2)
{ if( y % 4 == 0) leap = 1;
if( y % 100 == 0) leap = 0;
if( y % 400 == 0) leap = 1;
}
return [0, 31,28,31,30,31,30,31,31,30,31,30,31][ m] + leap;
}(编辑)或根据注释,使用Date对象的行为调整为超出预期的行为:
function monthDays( y, m)
{ return new Date(y, m, 0).getDate();
}发布于 2016-02-05 12:21:52
HTML
<input id="first" value="1/1/2000"/>
<input id="second" value="1/1/2001"/>
<script>
alert(datediff("day", first, second)); // what goes here?
</script>JavaScript
function parseDate(str) {
var mdy = str.split('/')
return new Date(mdy[2], mdy[0]-1, mdy[1]);
}
function daydiff(first, second) {
return Math.round((second-first)/(1000*60*60*24));
}来源:How do I get the number of days between two dates in JavaScript?
发布于 2016-02-05 12:41:14
function days_between(date1, date2) {
// The number of milliseconds in one day
var ONE_DAY = 1000 * 60 * 60 * 24;
// Convert both dates to milliseconds
var date1_ms = date1.getTime();
var date2_ms = date2.getTime();
// Calculate the difference in milliseconds
var difference_ms = Math.abs(date1_ms - date2_ms);
// Convert back to days and return
return Math.round(difference_ms / ONE_DAY);
}https://stackoverflow.com/questions/35214968
复制相似问题