C#: calculating time diff - c#

using the following:-
TimeSpan diff = dt2.TimeOfDay - dt1.TimeOfDay;
d1, d2 are 2 variables of type DateTime and they have got values in them
Now I want to check if there's a difference of 12 hours b/w them
if(diff>12)
{
//do stuff
}
now of course it wont wont coz 12 is an int..so how do I check if the time is more than 12 hrs or not ?? need help with this if statement only..thnx

The general solution is to construct a TimeSpan object that corresponds to the cut-off:
if(diff > TimeSpan.FromHours(12))
{
...
}
If the cut-off corresponds to a multiple of a 'nice' unit of time like days, hours, minutes, seconds or milliseconds as in your example, you could use the TotalXXX property of TimeSpan, as others have posted:
if(diff.TotalHours > 12)
{
...
}

To plainly answer your question, you use one of the properties on the TimeSpan struct, typically the TotalHours property. There are other, simpler, answers here that tells you how to do that, so I won't repeat it.
However, this means I must trust your question to be complete, and I think that just ignoring the date portion will give you edge-cases that you at least need to know about.
For instance, with the following two time-of-day values, how much time is between them?
18:00
08:00
Is it -10 hours, or 14hours between these two?
To properly answer your question, personally I would want you to tell me how you intend to use these values, what it means to you, and give a few examples.

use
if( diff.TotalHours > 12){
....
}

Have you actually used intellisense and noticed the Hours and TotalHours properties on the diff TimeSpan object?

TimeSpan.FromHours you need to use to find the difference

TimeSpan diff = dt2.Substract(dt1);
if (diff.TotalHours > 12)
{
// Do something
}

Related

Time-dependent coloring in C#

I need time-dependent coloring in a project. If the system is 10 minutes past the entrance time, the background will be orange. If it is 20 minutes past it will be red. I found the difference between the two dates using the
DateTime.Parse(timeNow).Subtract(DateTime.Parse(timeLogged));
but I can't compare the result.
if(Convert.ToInt32(DateTime.Parse(timeNow).Subtract(DateTime.Parse(timeLogged)))>10)
Does it have a similar use? Can you help me how to do it?
I am using Google Translate because my English is not very good, and I apologize for the language mistakes I made.
You can subtract DateTime objects. You'll get a TimeSpan. You can use that TimeSpan to determine the difference between the original objects:
DateTime now = DateTime.Parse(timeNow);
DateTime logged = DateTime.Parse(timeLogged);
TimeSpan diff = now - logged;
if (diff.TotalMinutes > 10)
// It's been more than 10 minutes.
You could do this aswell
// If older than 20 min
if(DateTime.Parse(timeLogged) < DateTime.Now.AddMinutes(-20))
{
// Do stuff
}
DateTime.Subtract returns a Timespan object that has a TotalMinutes property, so you could do this:
if (DateTime.Parse(timeNow).Subtract(DateTime.Parse(timeLogged)).TotalMinutes > 10)

C# 2 DateTime are not equal

I have one strange problem that I'm trying to understand.
In my controller there are 2 DateTime objects that I want to compare.
You can see screenshot from a debugger in my controller. I create one date time and get another one from a model.
At this step you can see in debugger that date1 differs from date2 for 2 seconds
At the next step I remove 2 seconds from date2 and compare it with date1
Cay you explain me why is it false? In debugger I see both of them the same.
Solution: As it was told in the comment, the idea was to check also milliseconds, I completely forgot about it!
As you can see in the reference source, a comparison of two DateTime objects is done through their respective ticks, which is their internal representation.
Comparing two DateTime values is a bit like comparing two floating point values: the difference might be so small that you're likely to not get what you want. Perhaps you need to check if they're on the same date, or if one falls in a specific range of the other.
The way to compare Datetimes is done by comparing their Tick property:
bool r = date1.Ticks == date2.Ticks;
Try this.
You can use DateTime.Compare to see which time is earlier/later. Also like people have already mentioned difference could be in e.g. milliseconds
How to use DateTime.Compare:
https://msdn.microsoft.com/en-us/library/system.datetime.compare(v=vs.110).aspx

Display items that are no more than 6 months old

What is the correct method to display items that are no more than 6 months (180 days) old? I'm using the following code, but it seems to be showing items that don't fit the criterion accurately.
DateTime.Now.Subtract(Convert.ToDateTime(e.DateCreated)).Days <= 180
Where could I have gone wrong?
Edit
Thanks everyone for your help. Turns out the hours were a key factor in deciding the age of an item. I don't really need it to be accurate to the hour, just to the date.
I would just use this to get a date six months ago
var sixMonthsAgo = DateTime.Now.AddDays(-180);
and then compare it with whatever you want to compare. I guess
if (Convert.ToDateTime(e.DateCreated) >= sixMonthsAgo)
in your case.
EDIT:
I performed a test with a test value provided in comments.
var input = DateTime.Parse("2013-06-23 18:14:47.937");
My current date is 21.12.2013 and time is about 11:00 AM.
With that defined, your code yields a result
180.16:39...
So it still meets your requirements, since it is exactly 180 days old + few hours and minutes.
My code yields a result
24.6.2013 about 11:00 AM
and since your date is 23.6. then it is older then the result and therefore does not meet your requirements.
As you can see, the hours play a big role here. So in the end, it very much depends on how you define "180 days ago". If you still feel that neither of the variants work well, give me at least 10 days you compare, both where it works and where it does not work and mark which should be older and which not.
TimeSpan ts = DateTime.Now - Convert.ToDateTime(e.datecreated);
if (ts.TotalDays <= 180)
{
//perform some task
}

difference between two date times

I want to calculate the difference between two DateTimes. This is what I have:
if ((DateTime.Now.Date - TheUTCDateTime.Date).TotalMinutes > 180)
{
ValidObject = false;
}
Basically, I want to make sure that TheUTCDateTime is not more than 3 hours old. Is what I am doing the best way to do this?
You probably don't want to extract the date and maybe want to use UtcNow instead of Now.
You can also use TimeSpan.FromHours for the period:
if ((DateTime.UtcNow - TheUTCDateTime) > TimeSpan.FromHours(3))
or simply
ValidObject = (DateTime.UtcNow - TheUTCDateTime) <= TimeSpan.FromHours(3);
Your approach is ok, but you could improve it a little bit:
TimeSpan span = DateTime.Now - TheUTCDateTime.Date;
ValidObject = span.TotalHours <= 3;
Since you want to check the hours i have used TotalHours, i have used DateTime.Now instead of Date which truncates the time and i set it also to true whereas your code only sets it to false.
If you want to check whether TheUTCDateTime is older than 3 hours, you shouldn't be using the .Date property:
DateTime.UtcNow - TheUTCDateTime > TimeSpan.FromHours(3)

What variable should I use if I want to save time values?

I want to make an app that adds 1 minutes and 25 seconds to a TimeLeft variable.
Problem is I have no idea what type of variable this should be, or even how to add 1 minutes 25 seconds to the available time left.
Any guidance would be much appreciated. I'm good with C#, but since I've never done something like, I'm in the dark.
I would suggest you use a DateTime variable. This will let you manipulate the time. If you want to add 1m 25s to a varible, you could simply use:
DateTime newTime = DateTime.Now.AddSeconds(85);
That will add 85 seconds onto the current time (or, in your case, TimeLeft as long as the TimeLeft variable is also a DateTime type)
TimeSpan works well. It's specifically designed to hold a duration of time.
Use the DateTime type. Assuming your TimeLeft variable is an integer, you probably need to convert it to DateTime type first and then perform the add. More information here

Categories

Resources