I am attempting to get the number of orders from the last 24 hours from a third party system.
I havent used DatetimeOffset before so eventually figured out how to subtract 1 day from the current day. I then created some dummy records and set their value to yesterday but with the below code it doesnt seem to work (im expecting 3 orders to come through from the 4 as their date is set to yesterday.
ordersTierAmount(DateTimeOffSet.UtcNow);
int ordersTierAmount(DateTimeOffset datetime)
{
var ts = new TimeSpan(1, 0, 0, 0);
var all = GetAll();
var count = all.Count(i => i.ConfirmedDateTime == datetime.Subtract(ts));
return count;
}
List<Order> GetAll()
{
return new List<Order>
{
new Order { Id = "1", ConfirmedDateTime = new DateTimeOffset(new DateTime(2024,06,02)) },
new Order { Id = "2", ConfirmedDateTime = new DateTimeOffset(new DateTime(2024,06,02)) },
new Order { Id = "3", ConfirmedDateTime = new DateTimeOffset(new DateTime(2024,06,02)) },
new Order { Id = "4", ConfirmedDateTime = new DateTimeOffset(new DateTime(2024,06,01)) }
};
}
public class Order
{
public string Id { get; set; }
public DateTimeOffset ConfirmedDateTime { get; set; }
}
Where am i going wrong? What have i missed for the correct number of orders not to appear?
I read up on MSDN as i think i did the subtract wrong https://learn.microsoft.com/en-us/dotnet/api/system.datetimeoffset.subtract?view=net-8.0
>Solution :
The problem is that the DateTimeOffset that you’re passing to the ordersTierAmount() method has a non-zero Time component, so comparison with the dummy dates (which have no Time component) will return false.
Change this:
var count = all.Count(i => i.ConfirmedDateTime == datetime.Subtract(ts));
to this:
var count = all.Count(i => i.ConfirmedDateTime.Date == datetime.Subtract(ts).Date);
and you should find that you get the result you expect.
(Please note that while this is intended to answer your question, it might not be the behaviour you want.)