Murthy
Murthy

Reputation: 1552

How to compare 2 DateTime in C#

I want to find if there are any difference between DateTime.UtcNow.

LastEdited(9/11/2011 21:00:00) is less than 30 minutes, so the bool value should return a false since the difference is higher.

But it returned true. May I know what is wrong here?

 bool difference = ((DateTime.UtcNow - LastEdited).Minutes < 30);

Upvotes: 3

Views: 3625

Answers (6)

Till
Till

Reputation: 3154

While your code will work fine when using .TotalMinutes instead of .Minutes i would suggest using

bool isLessThan30MinutesOld = (LastEdited.AddMinutes(30) > DateTime.UtcNow);

To me that's just easier to read and understand.

Upvotes: 0

MPelletier
MPelletier

Reputation: 16657

Alternative:

 bool difference = (DateTime.UtcNow - LastEdited) < new TimeSpan(0,30,0);

The only gain here is if what you're calculating your differentiating with (30 minutes) gets more complex.

Upvotes: 0

AnandMohanAwasthi
AnandMohanAwasthi

Reputation: 839

Try this way

                UtcNow = Convert.ToDateTime(UtcNowtxt.Text.Trim());
                LastEdited = Convert.ToDateTime(LastEditedtxt.Text.Trim());
                TimeSpan GetDiff = (LastEditedtxt).Subtract(UtcNow);
                if (GetDiff.Minutes < 30)
                {
                    //Do something
                }

Upvotes: 0

&#216;yvind Br&#229;then
&#216;yvind Br&#229;then

Reputation: 60684

Use TotalMinutes instead of Minutes.

Minutes is just the minute part of the difference, so 1 hour and 10 minutes will cause Minutes to be 10, while TotalMinutes will cause it to be 70.

Upvotes: 2

V4Vendetta
V4Vendetta

Reputation: 38200

Did you try using

bool difference = ((DateTime.UtcNow - LastEdited).TotalMinutes < 30);

The result is actually a Timespan and if you check for TotalMinutes it gives you the entire span part in minutes while Minutes would give only the actual minute component of the Time interval.

Upvotes: 9

vc 74
vc 74

Reputation: 38179

You are looking at the minutes component in the time span. Check TotalMinutes instead.

Upvotes: 8

Related Questions