MOMM JS日期差异作为月份

发布于 2025-02-03 08:20:49 字数 204 浏览 4 评论 0 原文

我正在尝试在当前时间到2021年12月1日下午4点之间的区别。有6个月零2小时的差异。在这种情况下,我希望答案类似于6.02。但是5.98即将到来。我该如何得到我想要的答案?

在此处输入图像描述

I'm trying to get the difference between current local time and December 1, 2021 at 4 pm. There is a difference of 6 months and 2 hours. In this case I expect the answer to be something similar to 6.02. But 5.98 is coming. How can I get the answer I want?

enter image description here

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

若相惜即相离 2025-02-10 08:20:49

根据 now.diff(日期,'note,true),它应该返回一个大于6的浮点数。

现在。 diff(date)返回这两个时间点之间的毫秒差。调用 moment.duration({milliseconds})。Asmonths()不是理想的,因为有些月可能是30天,而其他人可能长31天。看来那一刻。为了解决这个问题,Moment.js讨论了文档中的日历差异:

moment#diff 具有针对一个月和年差异的特殊处理。优化的是确保两个月的日期始终是整个数字。

所以1月15日至2月15日应该是1个月。

2月28日至3月28日应该是1个月。

2011年2月28日至2012年2月28日应完全是1年。

According to the moment.js docs, the standard way to get the difference between two dates in your example would be now.diff(date, 'months', true), which should return a floating point number greater than 6.

now.diff(date) returns the millisecond difference between those two points in time. Calling moment.duration({milliseconds}).asMonths() is not ideal because some months may be 30 days long and others may be 31 days long. It appears that moment.js uses somewhere in between 30 and 31 days as the duration of one month. To address this issue, moment.js have discussed calendar diffs in the docs:

moment#diff has some special handling for month and year diffs. It is optimized to ensure that two months with the same date are always a whole number apart.

So Jan 15 to Feb 15 should be exactly 1 month.

Feb 28 to Mar 28 should be exactly 1 month.

Feb 28 2011 to Feb 28 2012 should be exactly 1 year.

何止钟意 2025-02-10 08:20:49

“一个月”的定义只能是一个“模糊”,因为日历的几个月的长度不同。定义的一种方法是将年度分为12个平等部分,并将其用作“月份”:

function monthsUntil(year,month,day,hour=0){
 const trg=new Date(year,month-1,day,hour,0,0), 
  now=new Date(), nxt=new Date();
 nxt.setFullYear(nxt.getFullYear()+1);
 return (12*(trg-now)/(nxt-now)).toFixed(4);
}

console.log(monthsUntil(2022,12,1,16))

The definition of "a month" can only be a "fuzzy" one, as the months of the calendar are of different lengths. One way of defining it would be to divide the year into 12 equal parts and use that as a "month-metric":

function monthsUntil(year,month,day,hour=0){
 const trg=new Date(year,month-1,day,hour,0,0), 
  now=new Date(), nxt=new Date();
 nxt.setFullYear(nxt.getFullYear()+1);
 return (12*(trg-now)/(nxt-now)).toFixed(4);
}

console.log(monthsUntil(2022,12,1,16))

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文