打字稿时刻日期差异

发布于 01-09 01:31 字数 837 浏览 1 评论 0原文

我在使用时刻来计算天数差异时遇到了几个问题。让我暴露我的问题:

我必须从今天的日期中减去一个日期。例如 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 技术交流群。

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

发布评论

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

评论(1

你丑哭了我2025-01-16 01:31:02

我相信您正在寻找的是这样的:

moment("28/02/2022", "DD/MM/YYYY").diff(moment().startOf('day'), 'days')

顺便说一句,diff 中不需要双 moment(),ass diff 采用 moment 实例,无论源如何。

I believe what you are looking for is this :

moment("28/02/2022", "DD/MM/YYYY").diff(moment().startOf('day'), 'days')

By the way, no need for that double moment() in the diff, ass diff takes moment instance what ever the source.

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