2

When I look in my database, the Date field of the Connections table, wich type is DateTime, has the value 2012-03-01 01:49:02.097.

But when I want to check if the user connected in the last hour :

if (user.Connections.Max(t => t.Date).Date.AddHours(1) > DateTime.Now)

The time part of the Date is always zero.

So my code only works between midnight and 1 hour in the morning haha!

Thanks for the help!

1 Answer 1

6

There are two meanings of .Date in this, which is making for some confusion; here:

t => t.Date

this means "access the member called Date, a DateTime"; so here:

.Max(t => t.Date)

this means "find the maximum over all Date members, a DateTime"

However! This:

).Date.A
 ^^^^^

means "take the date-only part of this value" (any DateTime has a .Date member which is the date-only part of the value); so yes: that goes to midnight, then you add an hour. So; don't do that! What you want is probably:

if (user.Connections.Max(t => t.Date).AddHours(1) > DateTime.Now)

or perhaps more efficiently:

var cutoff = DateTime.Now.AddHours(-1);
if (user.Connections.Any(t => t.Date > cutoff)) {
    ...
}

sine that can short-circuit.

Sign up to request clarification or add additional context in comments.

1 Comment

I should use more significant names in my database!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.