How do I add time together? - c#

I am working on a timesheet program in C# where the user selects hours worked for a day from a combobox drop down list for each day the work. The dropdown options are in 15 minute increments ( :15, :30, :45, 1:00, 1:15 and so on). So on Monday, the user could select 5:30 (meaning he/she worked 5 hours and 30 minutes, not the time 5:30). On Tuesday, the user could select 6:45 and so on for the week.
The Selected Item is for the total hours and minutes worked that day, not an interval of time or a specific point in time, but the total hours and minutes worked for the day.
How can I add the hours and minutes selected each day together to get a grand total for the week?
It is my understanding, the items in a combobox are strings, so I tried to convert the strings to DateTime, but that didn't work. I tried converting the string to a decimal and then to DateTime, but I was unable to do that either.
How do I take those hours/minutes worked each day, and get a total for the week?
Help!? I am losing my mind on this one!! :)

I tried to convert the strings to DateTime, but that didn't work.
Convert strings to integers, which represent minutes. Construct TimeSpan objects from these integers, passing the integer for the middle parameter.
Add TimeSpan objects together using operator +. The result will give you the total time, expressed as a span of time, from which you can query hours, minutes, and even days, if necessary.

Sometimes this may be a workaround for the current situation, anyway keep it as a suggestion;
Let timeList be the list of string that you are getting as inputs(please use 0:15 for 15 minutes).
List<string> timeList = new List<string>();
timeList.Add("0:15");
timeList.Add("2:00");
timeList.Add("1:00");
timeList.Add("2:15");
timeList.Add("3:15");
timeList.Add("4:15");
Then you can process the result by using the following code:
TimeSpan totalTime = new TimeSpan(0, (int)timeList.Sum(x => getMinutes(x)), 0);
Where the getMinutes()method is defined like the following:
public static double getMinutes(string timeIn)
{
string[] components = timeIn.Split(':');
TimeSpan ts = new TimeSpan(int.Parse(components[0]), int.Parse(components[1]), 0);
return ts.TotalMinutes;
}
Working Example

The combobox item should be a TimeSpan which can be added together.

Related

Difference between two times follow up (Convert to decimal)

I asked a question like this earlier and got a great answer but I made a mistake and wanted the output to be a decimal rather than a time. So here's the question.
I have two textboxes that allow a user to enter a start time and an end time in this format (h:mm). I want it to return the difference in a label. For example, if a user enters 1:35 in the first textbox and 3:30 in the second textbox and press the 'Calculate' button, it will return the decimal 1.92.
Any ideas or resources for this? I only want to calculate decimal difference of the time entered, date and seconds doesn't matter at all. Below is the code for getting an output in the format of (h:mm).
TimeSpan ts1 = TimeSpan.Parse(textBox1.Text); //"1:35"
TimeSpan ts2 = TimeSpan.Parse(textBox2.Text); //"3:30"
label.Text = (ts2 - ts1).ToString(); //"1:55:00"
It sounds like you want the total number of hours, in that 1.92 hours is 115 minutes (ish).
In that case you want:
double hours = (ts2 - ts1).TotalHours;
... you can then format that how you wish (e.g. to 2 decimal places).
For example:
TimeSpan ts1 = TimeSpan.Parse("1:35");
TimeSpan ts2 = TimeSpan.Parse("3:30");
double hours = (ts2 - ts1).TotalHours;
Console.WriteLine(hours.ToString("f2")); // Prints 1.92
Of course I'd personally use Noda Time and parse the strings as LocalTime values instead of TimeSpan values, given that that's what they're meant to be (times of day), but that's a minor quibble ;)
(ts2 - ts1).TotalHours.ToString();

Get Hours and Minutes from Datetime

Out Time :
2013-03-08 15:00:00.000
In Time :
2013-03-08 11:21:03.290
I need to get Hours and Minutes separately for same date from above, when (Out Time - In Time).
How can I do that ?
I think you probably just want:
TimeSpan difference = outTime - inTime;
int hours = (int) difference.TotalHours;
int minutes = difference.Minutes;
Note that Minutes will give you "just the minutes (never more than 59)" whereas TotalHours (truncated towards zero) will give you "the total number of hours" which might be more than 23 if the times are more than a day apart.
You should also consider what you want to do if the values are negative - either consider it, or explicitly rule it out by validating against it.
The Subtract method on the DateTime class will allow you subtract that date from the other date.
It will give you a TimeSpan which will be the difference.
I'll leave it to you to work out the actual code.
http://msdn.microsoft.com/en-GB/library/8ysw4sby.aspx
You can use Hours property and Minutes
link : http://msdn.microsoft.com/en-us/library/system.datetime.hour.aspx

Convert Date to Milliseconds

I am working with Visual Studio 2010, MVC 3 and C#. I am creating some highcharts and need to have the x-axis be a date. I am pulling the dates from a database and adding them to and array that will then be passed to highcharts. I think highcharts requires the dates to be in millisecond format. Ho do I go about converting a DateTime of '12/20/2011 5:10:13 PM" for example to milliseconds?
Once you figure out what you want to calculate milliseconds from, you can just take one DateTime object from another to get a TimeSpan object. From TimeSpan you can get TotalMilliseconds.
In other words, if start and end are DateTime objects, you can do this:
double milliseconds = (end - start).TotalMilliseconds;
You can use the DateTime.Ticks property and convert the value to milliseconds.
The value of this property represents the number of 100-nanosecond intervals that have elapsed since 12:00:00 midnight, January 1, 0001, which represents DateTime.MinValue. It does not include the number of ticks that are attributable to leap seconds.
A single tick represents one hundred nanoseconds or one ten-millionth of a second. There are 10,000 ticks in a millisecond.
The .Ticks in C# DateTime gives you the value of any time in ticks. You can thereafter convert to milliseconds as shown below:
long dateticks = DateTime.Now.Ticks;
long datemilliseconds = dateticks / TimeSpan.TicksPerMillisecond;
DateTime[] dates = ;
var minDate = dates.Min();
var msDates = dates.Select(date => (date - minDate).TotalMilliseconds).ToArray();

function which divides time period by periodicity

I need help to creating a function that can divide a period of time into regular periodicity of year.
For example: I have a period from 11/10/2011 to 08/07/2012 divided on regular semester. I want to get this result in a list:
1- 11/10/2011 - 12/31/2011
2- 01/01/2012 - 06/30/2012
3- 07/01/2012 - 08/07/2012
As you said, it is little bit complex but not impossible. With small thought you might get this easily. I've implemented code but to give your brain some work I'm not posting the code but giving you pseudo code below.
I thought of following way. First you need to have a duration through which you want to divide a year, for ex: 6 months.
Take the start date and create a new date by using DateTime constructor (year, month, day) and pass the year in the start date as year and month and day as 1 as below:
new DateTime(startdate.Year, 1, 1);
This will give you start date of that year. Then add duration days/months to that date to get the next periodicity. If your start date is less than this new date then add once again duration to that new date till you get the date greater than start date.
With the above logic you can form the periods you want till the end date. Of course you have to check whether your end date as well against this periodicity. There are many other conditions you need to check to get the proper system to give these periods for any given start and end dates.

How to format a TimeSpan for hours not days

The following code
Console.WriteLine("{0:%h} hours {0:%m} minutes",
new TimeSpan(TimeSpan.TicksPerDay));
produces this output:
0 hours 0 minutes
What I would like is this output:
24 hours 0 minutes
What am I missing in this format string?
P.S. I know that I could manually bust up the TimeSpan into days and hours, and multiply the two but would rather use a custom format string, as these timespans are being displayed in a silverlight datagrid and people are expecting to see horus, not days.
According to MSDN, using %h will show you
The number of whole hours in the time interval that are not counted as part of days.
I think you will need to use the TotalHours property of the TimeSpan class like:
TimeSpan day= new TimeSpan(TimeSpan.TicksPerDay);
Console.WriteLine("{0} hours {1} minutes", (int)day.TotalHours, day.Minutes);
Update
If you absolutely need to be able to achieve the stated format by passing custom formatters to the ToString method, you will probably need to create your own CustomTimeSpan class. Unfortunately, you cannot inherit from a struct, so you will have to build it from the ground up.
There doesn't seem to be a format option for getting the total hours out of a TimeSpan. Your best bet would be to use the TotalHours property instead:
var mySpan = new TimeSpan(TimeSpan.TicksPerDay);
Console.WriteLine("{0} hours {1} minutes", (int)mySpan.TotalHours, mySpan.Minutes);
TotalHours returns a double as it includes the fractional hours so you need to truncate it to just the integer part.
Another possibility is:
TimeSpan day = new TimeSpan(2,1,20,0); // 2.01:20:00
Console.WriteLine("{0} hours {1} minutes", (int)day.TotalHours, day.Minutes);
Console will show:
49 hours 20 minutes

Categories