简体   繁体   中英

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.)

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.

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:

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...

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:

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;

How can I do this ?

You can remove transaction dates that are older than 10 days ago.

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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