Click here to Skip to main content
12,826,440 members (25,782 online)
Rate this:
Please Sign up or sign in to vote.
See more: C#
Hi How do I compare and get if time x is greater than time y?


DateTime x = DateTimeNow();
DateTime now = DateTime.Now;
TimeSpan diff = now - x;
System.Console.Write("File over stayed : time Differnece : " + diff); 

DateTime time = "00:30:00.000";
if (diff > time ) //This is where I get an Error
   System.Console.Write("File time too long : time Differnece : " + diff);
   System.Console.Write("File still new :"+diff);

Thanks in advance for your help.
Posted 22-Jan-13 1:50am
Updated 22-Jan-13 9:06am
Rate this: bad
Please Sign up or sign in to vote.

Solution 3

DateTime is a point in time, where as TimeSpan is a duration.
With this in mind, think of it!

The difference between two points in time is a duration.
E.g. the difference between yesterday noon (a point in time) and today noon (a point in time) is 24 hours (a duration).

The difference between two durations is a duration again.
E.g. the difference between 5 minutes (duration) and 3 minutes (duration) is 2 minutes (duration).

Now you can elaborate yourself what it means to add/subtract durations/points in time to/from durations/points in time.
Some combinations may not be meaningful, though.

Finally, the DateTime and TimeSpan may not provide all possible operations from above.

Rate this: bad
Please Sign up or sign in to vote.

Solution 1

DateTime first = GetFirstDate();
DateTime second = GetSecondDate();

if (first.Date.Equals(second.Date))
    // the dates are equal

in linq:

e => DateTime.Compare(e.FirstDate.Value, SecondDate) >= 0
BobJanova 22-Jan-13 11:38am
This doesn't answer the question. It also implies that DateTime.Equals and DateTime.Compare are the same thing, which they aren't.
Sergey Alexandrovich Kryukov 22-Jan-13 12:56pm
Of course.
Rate this: bad
Please Sign up or sign in to vote.

Solution 2

You are comparing a DateTime to a TimeSpan. I think you meant
TimeSpan time = new TimeSpan(0, 30, 0);
if(diff > time) ...
Sergey Alexandrovich Kryukov 22-Jan-13 12:57pm
You can compare either DateTime or TimeSpan, apparently, with completely different meaning.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

    Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy | Mobile
Web02 | 2.8.170326.1 | Last Updated 22 Jan 2013
Copyright © CodeProject, 1999-2017
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100