Calculate difference between 2 datetimes (Timespan + double) - c#

I have a list that holds Datetimes.
To calculate the difference between 2 DateTime i use TimeSpan.
public static List<DateTime> list = new List<DateTime>();
TimeSpan ts = new TimeSpan();
double result = 0;
ts = DateTime.Now - list[list.Count-1];
result = ts.TotalSeconds;
When debugging this code both the DateTime.Now and the list[list.Count-1] have DateTimes where the DateTime.Now is off course higher then the value of the list.
But for some reason i keep getting 0 in the variable result, how come exactly?
Best regards, Pete

I just tried the following, works perfectly okay.
List<DateTime> list = new List<DateTime>();
list.Add(DateTime.Now.AddDays(-1));
list.Add(DateTime.Now);
list.Add(DateTime.Now.AddDays(1));
TimeSpan ts = new TimeSpan();
double result = 0;
ts = DateTime.Now - list[list.Count - 1];
result = ts.TotalSeconds;
Attached the debbuging picture:
Reasons for not working could be:
Either your list is not being populated
Or the value of ts.TotalSeconds is smaller than double range (Which can be practically not possible.)

First comment, you don't need = new TimeSpan(); - you're only discarding this anyway when you set ts again further down.
What line is your debugger on when you see the value of 0 for result? Have you stepped over the line where result is set? If you are on the line, then that line has not yet actually run...

Instead of using
ts = DateTime.Now - list[list.Count-1];
use
ts=DateTime.Now.Subtract(list[list.Count-1]

I think time difference is to small for seconds, it might be in mili seconds or even smaller. Try ticks like this.
result = ts.Ticks;

There is nothing wrong with the code you have posted (except I would suggest that you join declaration and initialization of your variables). I have to guess but perhaps you are "swallowing" exceptions and pass the empty list?
Then the line
ts = DateTime.Now - list[list.Count-1];
will throw an exception and result will retain it's value of 0.

list doesn't have any elements, so list.Count - 1 doesn't hit anything. also, there might not be an entire second to calculate. i added a time (using ticks) to subtract with. other than that, there's nothing wrong with what you have.
double result = 0;
List<DateTime> list = new List<DateTime>();
list.Add(new DateTime(123456));
TimeSpan ts = DateTime.Now - list[list.Count - 1];
result = ts.TotalSeconds;

Related

Get time difference between am and pm using time span

need to get time difference between 10 pm and 4 am. below is my code
_firstShiftStartTime = new TimeSpan(_oOrgShiftDetailDTO.StartTime.Value.Hour,_oOrgShiftDetailDTO.StartTime.Value.Minute, _oOrgShiftDetailDTO.StartTime.Value.Second);
_firstShiftEndTime = new TimeSpan(_ShiftDetailDTO.EndTime.Value.Hour, _ShiftDetailDTO.EndTime.Value.Minute, _ShiftDetailDTO.EndTime.Value.Second);
this returns two timespans 22.00.00 and 6.00.00. i need to get time difference between these two.
Using Stefano's Solution of using Subtract and then handling negative values
var difference = _firstShiftEndTime.Subtract(_firstShiftStartTime);
if (difference.Ticks < 0)
{
difference = new TimeSpan(TimeSpan.TicksPerDay - difference.Negate().Ticks);
}
Well i think you can do this
_firstShiftEndTime.Subtract(_firstShiftStartTime);
Like explained in the documentation
EDIT:
since you consider the negative values a not valid value I will do this
if (_firstShiftEndTime < _firstShiftStartTime)
_firstShiftEndTime.Add(TimeSpan.FromDays(1));
var myResult = _firstShiftEndTime.Subtract(_firstShiftStartTime);

DateTime difference in ticks does not match

I have the following code:
var a = (DateTime.Now.Subtract(DateTime.Now.AddTicks(8))).Ticks;
var b = (DateTime.Now - DateTime.Now.AddTicks(8)).Ticks;
When I check the values I see that:
a = -78
b = -20
How come? Shouldn't both be -8?
You are depending on the system to do everything at the same time, which it cannot. Each time you get DateTime.Now, it has a different value.
A quick experiment reveals that capturing the value of DateTime.Now in the beginning, and then performing operations on that:
var d = DateTime.Now;
var a = (d.Subtract(d.AddTicks(8))).Ticks;
var b = (d - d.AddTicks(8)).Ticks;
Yields the result you were expecting. a and b have the same value, -8.
Those lines of code take time to execute. It's never good to use Now more than once in single method or operation. Or Today, for that matter.

TimeSpan Time Calculation, Minutes - ho to convert time span to int

I have the folowing code,
now the question is what is the best way to preform this:
also take in notice the "minAdd" can pass 60, meaning 90min add (an hour an half etc)
thanks,
int minAdd = Convert.ToInt16(txtMinAdd.text);
DateTime now = DateTime.Now;
DateTime nextEvent = DateTime.Now.AddMinutes(minAdd);
TimeSpan diff = now - nextEvent;
if (diff > minAdd) -------------- PROBLEM HERE
{
//act here
}
EDIT: As noted by Reed, the code you've shown is pretty pointless. I assume you actually want to get nextEvent from somewhere else.
I suspect you just want:
if (diff.TotalMinutes > minAdd)
{
}
Or you could use:
TimeSpan minTimeSpan = TimeSpan.FromMinutes(Convert.ToInt16(txtMinAdd.text));
...
if (diff > minTimeSpan)
{
}
Since diff is based on nextEvent, which is based exactly on minAdd, there is no reason for this check - it will never be true.
Also, in your code, diff will always be negative if minAdd is positive, as you're subtracting a future event (nextEvent) from DateTime.Now.
If you are trying to schedule an event to occur at a point in time, you may want to consider using a Timer, and scheduling the timer to occur at some point in time based on the event time:
DateTime nextEvent = DateTime.Now.AddMinutes(minAdd);
TimeSpan diff = nextEvent - DateTime.Now;
// Schedule a timer to occur here
someTimer.Interval = diff.TotalMilliseconds; // Timer intervals are typically in ms

How can I segregate properties of DateTime?

I would like to write: if the result of the difference of 2 DateTimes is longer than 3 hours then.... stuff in the if statement happens. But I only need properties in seconds or minutes, can I extract just that from the DateTime object?
if(diffResult > DateTime.Hour(3))
{
}
I also want to know if its possible to divide DateTime by periods. Say I want to split my diffResult (which is the difference between 2 DateTimes) into 3 periods or perhaps for every 3 seconds my counter gets one added to it.
For the first part:
You can subtract two DateTimes to get a TimeSpan there you can get the total of various units - for example:
if ( (secondTime - firstTime).TotalMinutes > 180.0) ...
or you could use TimeSpan directly:
if (secondTime - firstTime > TimeSpan.FromHours(3)) ...
for the secondpart you have to do some calculation yourself:
var diff = secondTime - firstTime;
var period = TimeSpan.FromSeconds(diff.TotalSeconds / 3.0);
for (var time = firstTime; time < secondTime; time += period)
{ /* do your stuff */ }
U can compare using the follow code:
DateTime dt = new DateTime();
dt = DateTime.Now;
dt.AddHours(3);
int h = (int)DateTime.Now.Hour;
if (dt.Hour == h )
//Do something
else
//do otherthing
You can do this:
TimeSpan time = new TimeSpan(3, 0, 0);
if (date1.Subtract(date2) > time)
{
//YourCode
}
For the second, this article should be useful:
http://www.blackwasp.co.uk/TimespanMultiplication.aspx
The methods your asking about return integer results. What exactly is your question? DateTime.Hour(3) would not even compile.
I think you are looking for DateTime.Now.AddHours(3.0)
I should be clear, the only reason this answer is this sparse, is because of the invalid code in the author's question which. Since I don't attempt to guess at what people actually want, its up to the author, to clarify what he wants exactly.
All he has to do is subtract two DateTime values and compare it to a TimeSpan

Check difference in seconds between two times

Hi all I am currently working on a project where when a certain event happens details about the event including the time that the event occurred is added into a list array.
Once the method has finished I then pass on the list to another method that checks its values. Before I go through the loop I check the current time of my PC and I need to check whether the difference between the time saved in the list array and the current time is greater than 5 seconds.
How would I go about doing this.
Assuming dateTime1 and dateTime2 are DateTime values:
var diffInSeconds = (dateTime1 - dateTime2).TotalSeconds;
In your case, you 'd use DateTime.Now as one of the values and the time in the list as the other. Be careful of the order, as the result can be negative if dateTime1 is earlier than dateTime2.
DateTime has a Subtract method and an overloaded - operator for just such an occasion:
DateTime now = DateTime.UtcNow;
TimeSpan difference = now.Subtract(otherTime); // could also write `now - otherTime`
if (difference.TotalSeconds > 5) { ... }
This version always returns the number of seconds difference as a positive number (same result as #freedeveloper's solution):
var seconds = System.Math.Abs((date1 - date2).TotalSeconds);
I use this to avoid negative interval.
var seconds = (date1< date2)? (date2- date1).TotalSeconds: (date1 - date2).TotalSeconds;
The built-in DateTime.Subtract method can be used as follows
double diffInSeconds = dateTime1.Subtract(dateTime2).TotalSecond;
if (diffInSeconds > 5) { /* do stuff */ } ;

Categories