How to format a TimeSpan for hours not days - c#

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

Related

How do I add time together?

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.

Timespan in milliseconds to minutes and seconds only

I have a Timespan that is always in milliseconds, but I need to show the date in minutes and seconds only so that it's always "mm:ss". Even if there are hours in the timespan, the output string should contain only minutes and seconds.
For example, if there is a timespan of 02:40:30, it should get converted to 160:30.
Is there a way to achieve this?
Reed's answer is ALMOST correct, but not quite. For example, if timespan is 00:01:59, Reed's solution outputs "2:59" due to rounding by the F0 numeric format. Here's the correct implementation:
string output = string.Format("{0}:{1:00}",
(int)timespan.TotalMinutes, // <== Note the casting to int.
timespan.Seconds);
In C# 6, you can use string interpolation to reduce code:
var output = $"{(int)timespan.TotalMinutes}:{timespan.Seconds:00}";
You can format this yourself using the standard numeric format strings:
string output = string.Format("{0}:{1}", (int)timespan.TotalMinutes, timespan.Seconds);
I do it this way
timespan.ToString("mm\\:ss");
That is a pretty basic math problem.
Divide by 1000 to get total number of seconds.
Divide by 60 to get number of minutes.
Total seconds - (minutes * 60) = remaining seconds.

Comparing datetimes in eval to hours

I've got a datetime and I want to check if there is 24 hours difference between those two. I just don't know how to do that.
So far I've got this:
<%# (DateTime.Now - Convert.ToDateTime(Eval("new_date"))) < 24 ? "Today" : Eval("new_date") %>
It does not work tho :<
#Edit
And this is how datetime in my database looks like for example:
2016-09-18 12:26:14
The difference between 2 DateTimes is a TimeSpan, which has a TotalDays property you could compare to 1..
The result oft subtracting two DateTime values is a TimeSpan which has properties for hours, minutes, etc.
If you've got two DateTime values you can check whether the difference between them is less than 24 hours like this:
(DateTime.Now - otherDateTime).TotalHours < 24

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

Categories