打字稿时刻日期差异
我在使用时刻来计算天数差异时遇到了几个问题。让我暴露我的问题:
我必须从今天的日期中减去一个日期。例如 2022 年 2 月 28 日至 2022 年 2 月 21 日。以这种方式执行此操作:
const timeDifference = moment("28/02/2022", "DD/MM/YYYY").diff(moment(moment(), "DD/MM/YYYY"), "days");
这将返回 6 天
,因为它不包括我相信的最后一天。因为我需要它包含最后一天,所以我执行了以下操作:
const timeDifference = moment("21/02/2022", "DD/MM/YYYY")
.add(1, 'days')
.diff(moment(moment(), "DD/MM/YYYY"), "days");
This now returns 7
days,这正是我所需要的。
现在的问题是我有一个 if 语句,它执行以下操作:
if (timeDifference < 0)
现在,如果 timeDifference 是今天的日期,它会返回 0,但如果它是 20/02/2022,它也会返回 0,因为当我需要它返回-1。
我现在尝试采用不同的方法来执行此操作,
if (moment("20/02/2022") < moment.utc()) {
但是当日期小于今天的日期时,它将进入 if 语句,这不起作用。
Im having several issues using moment to calculate the difference in days. Let me expose my problem:
I have to subtract one date from todays date. For example 28/02/2022 - 21/02/2022. Doing this in this way:
const timeDifference = moment("28/02/2022", "DD/MM/YYYY").diff(moment(moment(), "DD/MM/YYYY"), "days");
This returns 6 days
as it doesnt include I believe the last day. Since I need it to include the last day I did the following:
const timeDifference = moment("21/02/2022", "DD/MM/YYYY")
.add(1, 'days')
.diff(moment(moment(), "DD/MM/YYYY"), "days");
This now returns 7
days which is what I need.
Now the problem is that I have an if statement
which does the following:
if (timeDifference < 0)
Now if timeDifference is todays date it returns 0 but if its 20/02/2022 it also returns 0 due to the .add when I need it to return -1.
I was now trying to do a different approach to do this if by doing
if (moment("20/02/2022") < moment.utc()) {
but this is not working when the date is less than todays date it will enter the if statement.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

我相信您正在寻找的是这样的:
顺便说一句,diff 中不需要双 moment(),ass
diff
采用moment
实例,无论源如何。I believe what you are looking for is this :
By the way, no need for that double moment() in the diff, ass
diff
takesmoment
instance what ever the source.