简体   繁体   English

以天为单位获取两个日期之间的差异

[英]Getting difference between two dates in days

I have a specific problem where I have records in my DB table like the following:我有一个特定的问题,我的数据库表中有如下记录:

LastUpdated

10 January 2017

(The dates are stored in the database as a DateTime type.) (日期作为 DateTime 类型存储在数据库中。)

Now I need to fetch the difference in days between today's date and the last one including today's date.现在我需要获取今天的日期和包括今天的日期在内的最后一个日期之间的天数差异。 So, for example, today is the 12th, so the amount of days would be 2.因此,例如,今天是 12 号,因此天数将为 2。

Now the second part of the problem is that I have another table setup like the following:现在问题的第二部分是我有另一个表设置,如下所示:

TransactionDate

1 January 2017
2 January 2017
3 January 2017
4 January 2017
5 January 2017
6 January 2017
7 January 2017
8 January 2017
9 January 2017
10 January 2017

So now after I perform a LINQ the updated results in my DBTable would look like the following:所以现在在我执行 LINQ 后,我的 DBTable 中的更新结果将如下所示:

3 January 2017
4 January 2017
5 January 2017
6 January 2017
7 January 2017
8 January 2017
9 January 2017
10 January 2017
11 January 2017
12 January 2017

So basically I'm trying to get the difference between the current date and the last updated date and then add it to the transaction details table.所以基本上我试图获得当前日期和上次更新日期之间的差异,然后将其添加到交易明细表中。 Upon adding the difference between two dates, I want to remove as much as the days in difference has been added, so that the total date span remains 10 days...添加两个日期之间的差异后,我想删除添加的差异天数,以便总日期跨度保持 10 天...

Can someone help me out with this?有人可以帮我解决这个问题吗?

Edit: this is the code so far:编辑:这是到目前为止的代码:

 var usr = ctx.SearchedUsers.FirstOrDefault(x => x.EbayUsername == username);
 var TotalDays = (DateTime.Now - usr.LastUpdatedAt).Value.TotalDays;

Is this a correct way of fetching the difference between two dates like I've mentioned above?这是获取我上面提到的两个日期之间差异的正确方法吗?

Now after this I perform an HTTP request where I get the remaining two dates and insert it like:现在,在此之后,我执行一个 HTTP 请求,获取剩余的两个日期并将其插入,如下所示:

ctx.TransactionDetails.Add(RemainingTwoDates);
ctx.SaveChanges();

Now I have dates expanding from 1st January to 12th of January, but I want to remove 1st and 2nd of January so that the total range of days stays 10;现在我的日期从 1 月 1 日扩展到 1 月 12 日,但我想删除 1 月 1 日和 2 日,以便总天数保持 10 天;

How can I do this ?我怎样才能做到这一点 ?

You can remove transaction dates that are older than 10 days ago.您可以删除早于 10 天前的交易日期。

ctx.TransactionDetails.Add(RemainingTwoDays);

//Now you want to remove those older than 10 days
var today = DateTime.Today;
var tenDaysAgo = today.AddDays(-10);
var oldTrandactions = ctx.TransactionDetails.Where(t => t.TransactionDate <= tenDaysAgo).ToList();

foreach (var t in oldTrandactions) {
    ctx.TransactionDetails.Remove(t);
}

ctx.SaveChanges();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM