How to get the time difference between two DateTime objects? - c#

emp = moduleEmployee.ReturnEmployeeDAO().FetchEmployeeByID(emp);
DateTime shiftStartTime = emp.Shift.StartTime;
DateTime shiftEndTime = emp.Shift.EndTime;
DateTime attTime = att.Time;
According to the above code my shiftStartTime is 11.00 PM and shiftEndTime is 7.00 AM. and attTime or signIntime is 1.00 AM. then how to calculate the difference between shiftStartTime and attTime. where the difference should be 2 hour.
please help.....
Thanks Rusho

If you subtract two DateTime objects, you get a TimeSpan.
A TimeSpan then has properties for TotalMilliseconds, TotalSeconds, etc.
You want the TimeSpan.TotalHours
int shiftHours = (attTime - shiftStartTime).TotalHours;

Just subtract one time from the other and you'll get a TimeSpan object.
see http://msdn.microsoft.com/en-us/library/1905yhe2.aspx

TimeSpan diff = att.Time.Subtract(emp.Shift.StartTime);

are you asking for something like this: ?
var timeSpan = (attTime - shiftStartTime);
the result is a TimeSpan where you can check how many hours, minutes, days, seconds and so on...

Related

Subtracting timespan from 24 hours

I'm trying to subtract my potentially negative timespan values from 24 hours to change them into positive values.
As an example case:
I want to find how much time is there till 8:00 AM.
If it's 16:00 PM now, timespan gives me -8 ish value so I want to substract it from 24 to get 16.
I'm trying this but it's giving me this error
The DateTime represented by the string is not supported in calendar
System.Globalization.GregorianCalendar.
What I tried ;
string startTime = String.Format("{0:t}", "8:00");
TimeSpan timeLeft = Convert.ToDateTime(startTime).Subtract(DateTime.Now);
if (timeLeft.TotalMinutes < 0 )
{
timeLeft = Convert.ToDateTime(String.Format("{0:H}","24:00")).Subtract(Convert.ToDateTime(timeLeft.Negate())) ;
}
How can I achieve subtracting my potentially negative timespans from 24 hours?
You are confusing TimeSpan and DateTime. I guess there is an easier way:
var eightOClock = TimeSpan.FromHours(8);
var now = DateTime.Now;
var till8again = now.TimeOfDay > eightOClock
? TimeSpan.FromHours(32) - now.TimeOfDay
: eightOClock - now.TimeOfDay;
So if TimeOfDay is less than eight hours (it's before 8am), we take the difference to 8am. If it's greater than 8am, we take the difference to 32hours, which is 8am tomorrow.
A DateTime is an absolute date, happening at a certain day, month, year... It must not be used to represent a specific hour.
So your attempt to convert "8:00", or "24:00" in a DateTime will forcibly fail.
For this you must use TimeSpan (or eventually an integer if you always work with hours).
You can use for example
if(DateTime.Now.TimeOfDay > TimeSpan.FromHours(8))
To see if it's more or less than 8:00.
TimeOfDay will return you the amount of time elapsed for today since midnight.
DateTime has also a lot of useful methods to Add or Substract time, see https://msdn.microsoft.com/fr-fr/library/system.datetime(v=vs.110).aspx for details
Use TimeSpan, and if the startDate is less the Now, add a day to it and then make the comparison.
TimeSpan startTime = new TimeSpan(8,0,0);
TimeSpan now = DateTime.Now.TimeOfDay;
startTime = startTime < now ? startTime.Add(TimeSpan.FromDays(1)) : startTime;
TimeSpan diff = startTime - now;
Another point: the error is coming from the fact that 24:00 doesn't represent 12:00 midnight. 0:00 represents midnight, and that will be a valid DateTime.

C# - Compute total hours between 8:00 to 2:00 AND 8:00 to 12:00

Here's my code
DateTime TimeIn = "8:00 AM",
TimeOut="2:00 AM";
double Total;
private void compute()
{
Total = (TimeOut - TimeIn).TotalHours;
}
8:00am to 2:00am should result 18 hours.But mine is resulting -7
Another problem is when i typed 24:00 as time out C# couldn't recognize it as Time.
It works properly when the TimeOout is less than 12:00am. like 11:59pm backwards.
(eg.: 11:30PM - 8:00AM) it computes properly.
Please Help.
Add +24 hours when negative result.
may be this could help you:
string TimeIn= "8:00 AM";
string TimeOut= "2:00 AM";
TimeSpan duration = DateTime.Parse(TimeOut).Subtract(DateTime.Parse(TimeIn));
The way you have declared the datetime Value is wrong. The right way to do it is by converting the string to datetime format
DateTime TimeIn = Convert.ToDateTime("08:00");
DateTime TimeOut = Convert.ToDateTime("02:00");
TimeSpan ts = TimeIn - TimeOut;
If you need the 18 hours span that you're looking for you'll have to pass the date value as well while assigning data to the variables

offset datetime with each other - Must tell the number of days in total

I must have built up such that I have a datetime which gets added antale day as it should go forward. and then I have time as it should set off in relation to 04/10/16 to 10/09/16
I do not care about the time which is in datetime. It should not I use for anything. What I need out of this is exactly how many days there are from that time.
Datetime dateString = "4/10/2016 8:30:52" //I pretend that it comes from the database, it was more in terms of see what come there.
DateTime dt = DateTime.Now.AddDays(5);
What I need out of this is that it tell me how many days there are in between the two datetime as I entered.
You can substract DateTime objects to obtain a TimeSpan:
Datetime dateString = DateTime.Parse("4/10/2016 8:30:52");
DateTime dt = DateTime.Now;
TimeSpan duration = dt-dateString;
From the TimeSpan object, you can get how many (full) days with :
int totalCompleteDays = (int)duration.TotalDays;
Or if you want a rounded results :
int roundedTotalDays = (int)Math.Round(duration.TotalDays);
DateTime objects support basic operators and will return TimeSpan objects.
DateTime DateTimeB = DateTime.Now.AddDays(5);
DateTime DateTimeA = DateTime.Now;
TimeSpan difference = DateTimeA - DateTimeB;
...
you can then use the TotalDays property of the timeSpan.
...
Console.out.WriteLine(difference.TotalDays);

How to get a DateTime from total amount of seconds?

Let's say I have
int seconds = 43200;
(amount of seconds from the beginning of the current day, 00:00:00) and I want to get related DateTime representation ("12:00:00"). Is there any c# utility function?
You need the TimeSpan, then you can get the DateTime in this way:
TimeSpan timeOfDay = TimeSpan.FromSeconds( seconds );
DateTime dt = DateTime.Today.Add( timeOfDay );
It is not a DateTime representation, it looks like a TimeSpan representation to me instead.
For this, you can use TimeSpan.FromSeconds method like;
int seconds = 43200;
var ts = TimeSpan.FromSeconds(seconds);
If you really need to add this to generate current day midday, you can use DateTime.Today property and add this to that.
DateTime dt = DateTime.Today.Add(ts);
You can calculate it directly:
int seconds = 43200;
DateTime dateTime = DateTime.Today.AddSeconds(seconds);

Get just the time from System.DateTime

Hi I have a local variable of the type of System.DateTime. How can I get just the time? Thanks
DateTime.Now.TimeOfDay returns a TimeSpan representing the time of the day.
If this is for display purposes (As it normally is with these questions), you can simply use one of the following:
myDateTime.ToShortTimeString();
myDateTime.ToString("hh:mm:ss"); //for 12 hour clock
myDateTime.ToString("HH:mm:ss"); //for 24 hour clock
DateTime time = DateTime.Now.TimeOfDay
DateTime dt = DateTime.Now;
string time_now =dt.TimeOfDay.ToString();

Categories