convert min, sec to a 0.xxx notation in c# - c#

I am new to c#. For school I have to make an exercise that converts the hours, minutes and seconds to a numeric value. So 37 min and 30sec becomes 0.625. Anyone know how to do this?
thanks a lot

var duration = new TimeSpan(0, 37, 30);
string s = duration.TotalHours.ToString("0.###");
// s === "0.625"

Assuming that you want hours, minutes and seconds to be converted to hours, you would do it like this:
double result = hours + minutes/60.0 + seconds/(60.0 * 60.0);
This is because a minute is 1/60th of an hour and a second is 1/3600th of an hour (3600 == 60 * 60) so the calculation uses simple scaling.
I'm thinking that you will need to show these kinds of calculations rather than using TimeSpan, if the teacher is looking to see if you understand the conversion logic.

Won't provide a copy/paste ready solution (homework :-p), but the TimeSpan class has everything you need: Parse methods and constructors to build a TimeSpan from various times (hours, minutes,...) and properties to return results as minutes, hours...

You will first want to convert the hours, minutes and seconds to a total number of seconds. Then you can compare that to the number of seconds in one hour. Take care when doing integer devision, you will first have to convert to a double!

Related

How can i convert time to minutes using Sql queries e.g "02:30:05' to 150.5 minutes

I am working on a billing system and its based on time-in and time-out. Rate is R5 per 30 minutes charged to users for loaning an item.
I managed to get the Time difference and got time as "02:30:05" now how can i convert this time to minutes and have "02:30:00" = "150 min" so that I can be able to divide time by 30 minutes, to be able to multiply by the rate to generate my bill. as I can not divide Date time with a number. I want something like (150 min/30 min = 5 ans) , (5 ans * 5 rate = R25 bill) I hope its clear guys i'm a beginner so please do say if I'm not making any sense. thank you in advance for your help.
try this one. it will calculate total minutes
SELECT LTRIM(DATEDIFF(MINUTE, 0, TimeSpent))
FROM yourtable
TimeSpent will be your datetime variable
I believe that you are getting time difference in TimeSpan. Then you can use to get total minutes:
timeSpan.TotalMinutes;
If you have the result in string then you must tryparse to get timespan:
string time = "02:30:00";
TimeSpan timeSpan;
if (TimeSpan.TryParse(time, out timeSpan))
{
var aa = timeSpan.TotalMinutes;
}
Since you didn't mention what is your dbms I'll provide you with the syntax of SqlServer that gives the difference of 2 times on minutes:
SELECT DateDiff(mi, #timeIN, #TimeOut)
The first parameter allows you to choose in what datepart you need the difference.
For years write YY
For months write MM
For days write DD
For hours write hh
For minutes write mi
For seconds write ss

LINQ C# - How to show more then 24 hours using timespan

I have this line in code :
TalkTime = TimeSpan.FromMinutes((int)g.Sum(b => b.Field<int?>("talkTime"))).ToString("hh':'mm':'ss")
I need to show the time as total hours. using totalHours gives me for example 54.33 . I need it to be 54:33:00 ..
Any suggestions ?
54:33:00 != 54 hours, twenty minutes and zero seconds
I think your logic may be off as far as what you are intending to output as TimeSpan.TotalHours is going to output a double and not actually the proper number of minutes.
// Get your timespan (using the same number of minutes as expected)
var timespan = TimeSpan.FromMinutes(3260);
// This would output a double and not a string
timespan.TotalMinutes; // yields 55.3333 (i.e. 54 hours and 1/3 or 20 minutes)
So I don't believe that you would actually want to output 54:33:00 as that would not be correct as it would mean 54 hours and 33 minutes as opposed to the correct value of 54 hours and 20 minutes, which you can do through the String.Format() method :
// This would output 54:20:00, which should be your correct answer
String.Format("{0:00}:{1:00}:{2:00}",(int)timespan.TotalHours, timespan.Minutes,0)
So an example of your original code might look like :
var talktime = TimeSpan.FromMinutes((int)g.Sum(b => b.Field<int?>("talkTime")));
// Use your talktime to set your proper string variable
TalkTime = String.Format("{0:00}:{1:00}:{2:00}",(int)talktime.TotalHours, talktime.Minutes,0);
You can see a working example of this in action here.
TimeSpan.TotalHours returns the current time in the TimeSpan instance in terms of hours. So the 0.33 is 0.33 of an hour, not 33 minutes. Using math and custom format you can achieve what you are trying to do. Here is an example:
var time = new TimeSpan(54, 21, 0);
var hours = System.Math.Floor(time.TotalHours);
var minutes = System.Math.Ceiling((time.TotalHours - hours) * 60); // you can also use time.Minutes
Console.WriteLine(string.Format("{0:00}:{1:00}:{2:00}", hours, minutes, 0));
This takes the Floor of the TotalHours property to determine the hour component and calculates the minutes component by multiplying the fraction of the TotalHours property by 60. You can also use time.Minutes for the minutes component.
A value for TotalHours of 54.33 doesn't mean 54 hours and 33 minutes, it means 54 hours + 33/100 hour, which 54 hours and 33*60/100 minutes, which is 54 hours and 19.8 minute, or 54 hours, 19 minutes + 0.8*60 seconds = 48 seconds. So 54.33 hours is 54:19:48.
Assuming you want to display a value of decimal 54.33 into a string 54:19:48, I guess the best way is to create a class that implements both IFormatProvice and ICustomFormater. The ICustomFormatter.Format function will do the formatting for you the same way as described above:
Take the total hours and use Math.Floor to round down to a number of hours.
Use CultureInfo.DateTimeFormatInfo to investigate whether to add a semicolon or a forward slash, or whatever strange character
Use the remainder * 60 to calculate the (decimal) number of minutes
again: Math.Floor to calculate the number of full minutes and remainder to get the number of second
Do the same to get the number of seconds and number of milliseconds.
MSDN about IFormatProvider with an example of what to do in ICustomFormatter.Format

Calculate time difference using TimeSpan

I am trying to calculate the time difference of two given times slots but the answers does not seem to be correct what am I doing wrong?
My code:
For some reason the value given amFinish is changed from 16:30 to 16:18:00 I have no idea why!
And What if I have a text box and the user enters 16.30 how would I take that value and compute it as 16hrs and 30mins
The answer should be 05.30 but instead I get 05.18. Any sugestions?
30% of an hour is 18 minutes.
16.30 hours is 16 hours and 30/100 parts of an hour.
16 hours and a half would be 16.50.
You have decimal 16.3 hours, which is 16 hours and 18 minutes as Oded explains.
If you need to specify both hours, minutes, and seconds, use the overload of the TimeSpan constructor which takes three arguments:
TimeSpan amStart = new TimeSpan(0, 11, 0);
TimeSpan amFinish = new TimeSpan(16, 30, 0);
And if you need to convert a string into a TimeSpan, use something like:
TimeSpan amFinish = TimeSpan.ParseExact("16.30", #"hh\.mm", CultureInfo.InvariantCulture);

C# get time between two datetime range

Hello everybody i have asp.net mvc4 application where i made countdown something like this:
How i can get how many days, hours, minutes and seconds are remaining with two daetime range
i have tried this does not working on minutes .TotalMinutes
datetime.TotalDays();
Use
Timespan remtime = YourLaunchDateTime - DateTime.Now;
Then:
Use remtime.Days for Days
Use remtime.Hours for Hours
Use remtime.Minutes for Minutes
Use remtime.Seconds for Seconds
Do not use any Total... property as it converts all time into that entity.
You are using remtime.TotalMinutes. This will convert your Time into Minutes.
For eg. if 3 Hours are left this will return 180 Minutes (bcoz 3 * 60 = 180)
TimeSpan span = dateTime1 - dateTime2;
span will contain needed data.
You should use Minutes instead of TotalMinutes. TotalMinutes makes sum of all minutes within the timespan.

Time difference between 2 timespans fails to return expected data

I have created 2 Timespans below:
TimeSpan currentTs = TimeSpan.FromSeconds(43995); //12:13:15
TimeSpan towTime = TimeSpan.FromSeconds(303072); //12:11:12
I'm trying to find the difference in minutes (by the seconds I'm passing it, it looks like they are on different days). I am hoping for around 2 minutes difference, but in reality, I'm getting -57 minutes.
int timeDifference = (int)currentTs.Subtract(towTime).Minutes;
Can someone explain what i am doing wrong?
If you are just looking for the difference between the minutes (not including the days, hours or seconds), then you can use
double timeDifference = currentTs.Minutes - towTime.Minutes; // 2
This is just the difference of the minutes component though. As other people have said, these times are separated by 3 days, so a TimeSpan possibly isn't ideal.
Or, If you want the seconds to be included as well, you can use
TimeSpan minutes1 = new TimeSpan (0, currentTs.Minutes, currentTs.Seconds);
TimeSpan minutes2 = new TimeSpan (0, towTime.Minutes, towTime.Seconds);
double timeDifference = minutes1.TotalMinutes - minutes2.TotalMinutes // 2.05;
You are looking for the TotalMinutes property not Minutes - the later is just the minutes part of the time difference, the former is the full time difference expressed in fractional minutes:
double timeDifference = currentTs.Subtract(towTime).TotalMinutes;
Also easier to read is:
double timeDifference = (currentTs - towTime).TotalMinutes;
I'm guessing you want to completely ignore the fact that the times are different by about 3 days. In that case, if you take the remainder after division by 86400 (the number of seconds in a day) and pass that to TimeSpan.FromSeconds, you should hopefully get what you want:
TimeSpan currentTs = TimeSpan.FromSeconds(43995 % 86400); //12:13:15
TimeSpan towTime = TimeSpan.FromSeconds(303072 % 86400); //12:11:12, ignoring the 3 days.
double timeDifference = (currentTs - towTime).TotalMinutes;
I got the value of timeDifference as 2.05 when I tried this.
Of course, if currentTs is earlier in the day than towTime (perhaps because midnight falls between them), the time difference will come out negative. If you still want to count the number of minutes between the two, assuming that currentTs is always after towTime, then you'll need to add 1440 (the number of minutes in a day) to timeDifference if it works out negative:
if (timeDifference < 0)
{
timeDifference += 1440;
}
Because the second timespan isn't 12:11:12, its 3:12:11:12.
So you're going to get a negative result which would be in the thousands if you did total minutes (since its representing something like -2days, 57 minutes, 57 seconds)...since you just ask for Minutes and not TotalMinutes you just get the -57.
currentTime is less then towTime (you seem to be missing one digit).

Categories

Resources