I have a time span string like this: 20 min 49 sec
I would like to parse it TimeSpan instance, however I'm having bad time with it.
From the docs, it states that days and hours properties have to be set, but in my case I don't have them and I'd like to know if it's possible to make create such format where I can omit those values.
To parse that exact string, you'd use this expression:
TimeSpan.ParseExact(input, #"%m' min '%s' sec'", CultureInfo.InvariantCulture)
Basically, you treat every text other than where the numbers are as literal delimiters, specified using the 'xxx' syntax.
If you think you might need to handle both min and mins as well as sec and secs, you need to use the overload with multiple formats:
string[] formats = new[]
{
"%m' min '%s' sec'",
"%m' mins '%s' sec'",
"%m' min '%s' secs'",
"%m' mins '%s' secs'"
};
TimeSpan.ParseExact(input, formats, CultureInfo.InvariantCulture)
And contrary to what you think the documentation states, you don't have to specify days or hours at all, this is perfectly legal:
TimeSpan ts = TimeSpan.FromMilliseconds(45);
Related
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
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!
I have several strings in the format below:
"1:15"
":45"
"1:30:45"
I need them converted to a TimeSpan, but when I TimeSpan.Parse some of them (the first one, for example) it returns it as 1 hour and 15 minutes, where i would want it to be 1 minute and 15 seconds.
Any advice would be greatly appreciated!
You could use an overload of TimeSpan.ParseExact that allows you to specify an array of exact format specifiers.
var formats = new string[] {#"m\:s", #"\:s", ...};
var timeSpace = TimeSpan.ParseExact(input, formats, CultureInfo.CurrentCulture);
Note that ParseExact was introduced in .Net 4
The parameter string needs to be in the specific form specified below:
[ws][-]{ d | [d.]hh:mm[:ss[.ff]] }[ws]
So "1:15" will be treated as hh:mm. If you are passing 1 min 15 seconds, you need to reformat your parameter string to be "00:01:15". You can simply split your string to corresponding days, hour, min, ss variables and use those to assign your TimeSpan object.
MSDN has good documentation here:
http://msdn.microsoft.com/en-us/library/se73z7b9.aspx
I want to remove the seconds from timespan using c#
My code is here:
TimeSpan lateaftertime = new TimeSpan();
lateaftertime = lateafter - Convert.ToDateTime(intime) ;
It returns the value 00:10:00
But i want the below output :00:10 only not seconds field :00.
Well you can simply do as
string.Format("{0}:{1}", ts.Hours,ts.Minutes) // it would display 2:5
EDIT
to get it properly formatted use
string.Format("{0:00}:{1:00}", ts.Hours,ts.Minutes) // it should display 02:05
Note that a TimeSpan does not have a format. It's stored in some internal representation¹ which does not resemble 00:10:00 at all.
The usual format hh:mm:ss is only produced when the TimeSpan is converted into a String, either explicitly or implicitly. Thus, the conversion is the point where you need to do something. The code example in your question is "too early" -- at this point, the TimeSpan is still of type TimeSpan.
To modify the conversion to String, you can either use String.Format, as suggested in V4Vendetta's answer, or you can use a custom format string for TimeSpan.ToString (available with .NET 4):
string formattedTimespan = ts.ToString("hh\\:mm");
Note that this format string has the following drawbacks:
If the TimeSpan spans more than 24 hours, it will only display the number of whole hours in the time interval that aren't part of a full day.
Example: new TimeSpan(26, 0, 0).ToString("hh\\:mm") yields 02:00. This can be fixed by adding the d custom format specifier.
Custom TimeSpan format specifiers don't support including a sign symbol, so you won't be able to differentiate between negative and positive time intervals.
Example: new TimeSpan(-2, 0, 0).ToString("hh\\:mm") yields 02:00.
¹ TimeSpan is just a thin wrapper around a 64-bit integer containing the number of ticks (10,000 ticks = 1 millisecond). Thus, 00:10:00 will be stored as the number 6,000,000,000.
TimeSpan newTimeSpan = new TimeSpan(timeSpan.Hours, timeSpan.Minutes, 0);
Since there can be more than hours and minutes in a timespan string representation, the most reliable code for removing just the seconds and nothing else would be something like this:
var text = TimeSpan.FromDays(100).ToString(); // "100.00:00:00"
var index = text.LastIndexOf(':');
text = text.Substring(0, index); // "100.00:00"
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).