C# WinForms here.
I need to extract Seconds and Milliseconds from a similar string: "13.9" where 13 are Seconds and 9 Milliseconds.
To do this i use a String.Split() function and after i create a TimeSpan object with the corresponding values (suppose TimeString is "13.9"):
private TimeSpan TimeSplit(string TimeString)
{
var Seconds = Int32.Parse(TimeString.Split('.')[0]); //output 13
var Milliseconds = Int32.Parse(TimeString.Split('.')[1]); //output 9
var ts = new TimeSpan(0, 0, 0, Milliseconds, Decimals);
return ts;
}
Now i need to use the TimeSpan to show formatted output:
TimeSpan TempTs = TimeSplit(output);
SetTextMP(TempTs.ToString(#"hh\:mm\:ss\.ff"));
I need to have an output like: hh:mm:ss.ff but in my try Milliseconds(ff) stay fixed to 0. I checked and they are there..
As stated in the comments, the issue here is because 9 milliseconds amounts to 0.009 seconds. Running it with format specifier fff displays the complete millisecond value.
Related
I have time "00.05.415" (mm:ss.000) which is in string format.
I want to convert it to a TIME format where I can add multiple times such as "00.05.415"+"00.06.415"+"00.07.415" to get one single added time.
You'll want to use TimeSpan.ParseExact so you can specify the format that the time is in and then you can add the time spans together:
public static void Main(string[] args)
{
TimeSpan span1 = Convert("00.05.415");
TimeSpan span2 = Convert("00.07.415");
TimeSpan result = span1 + span2;
Console.WriteLine(result);
Console.ReadKey();
}
public static TimeSpan Convert(string span)
{
return TimeSpan.ParseExact(span, #"mm\.ss\.fff", CultureInfo.InvariantCulture);
}
https://msdn.microsoft.com/en-us/library/ee372287(v=vs.110).aspx
You'd want to take a look at the link that Avitus has and has the one here.
I'll have to ask why you'd want to add them together. You can't really 'add' times together .
One possible options is to to convert each to milliseconds and then formatting the resultant value.
5 seconds + 3.2 seconds could be:
5000 + 3200 = 8200.
You'd then use System.TimeSpan to convert that into days, hours, minutes ...etc
thanks for the correction Matt
If you know that the format is predefined to be mm:ss.000 you can do following to parse to TimeSpan:
var strings = "00:05.415".Split(new []{'.', ':'}, StringSplitOptions.RemoveEmptyEntries);
var minutes = int.Parse(strings[0]);
var seconds = int.Parse(strings[1]);
var milliseconds = int.Parse(strings[2]);
var time = new TimeSpan(0, 0, minutes, seconds, milliseconds);
And then you can add TimeSpans together.
If your format is not predefined use this 4KB script https://github.com/alekspetrov/time-input-js
It converts string/number into time format HH:MM:SS
Examples
00:00:00 -> 00:00:00
12:01 -> 12:01:00
12 -> 12:00:00
25 -> 00:00:00
12:60:60 -> 12:00:00
1dg46 -> 14:06
["notatime"] -> 00:00:00 + console warn
I have a TimeSpan field that adds up time spent on something. For example the time could be 33 hours, so the format is 33:56:00
I want to compare this to 10 hours to calculate how many over hours were done.
TimeSpan totalActualHours = new TimeSpan(0, 0, 0, 0, 0);
if (totalActualHours > TimeSpan.Parse(txtEstimateHrs.Text))
{
tmpOverHours = totalActualHours.Subtract(TimeSpan.Parse(txtEstimateHrs.Text));
}
But since totalActualHours is over 24 hours the format is coming out like 1.09:56:00 instead of 33:56:00. So txtEstimateHrs.Text is equal to 10 and I want to see if 33:56:00 is greater and if so then how many hours is it greater?
So the code is comparing if (1.09:56:00 > 10.00:00:00) so it never goes into the if statement.
The issue here is Timespan in converting the hours into days so 33 hours changes to 1 day and 9 hours, and the txtEstimateHrs.Text is an integar 10 and that changes to 10 days. I need both times to be in hours format and be able to compare them
You just need to properly construct the timespan object using the appropiate format. In your case, you can choose between
hour, min sec
day, hour, min, sec, millisec
Sample code:
Case 1
TimeSpan tmpOverHours;
TimeSpan totalActualHours = new TimeSpan(33, 56, 0);
TimeSpan hoursToCompare = new TimeSpan(int.Parse(txtEstimateHrs.Text), 0, 0);
if (totalActualHours > hoursToCompare)
{
tmpOverHours = totalActualHours.Subtract(hoursToCompare);
}
Case 2
TimeSpan tmpOverHours;
TimeSpan totalActualHours = new TimeSpan(0, 33, 56, 0, 0);
TimeSpan hoursToCompare = new TimeSpan(0, int.Parse(txtEstimateHrs.Text), 0, 0, 0);
if (totalActualHours > hoursToCompare)
{
tmpOverHours = totalActualHours.Subtract(hoursToCompare);
}
It seems you are having a parsing error when you are doing:
TimeSpan.Parse(txtEstimateHrs.Text)
if the text is "10" the parse method will interpret the value as days.
So you could change that code to something like:
TimeSpan.FromHours(int.Parse(txtEstimateHrs.Text))
Which will parse the number in the textbox into an int and use that to create a TimeSpan which correctly has the number of hours and not days.
Edit: On a side note, don't parse the text twice, better use a variable to hold the parsed TimeSpan and then use it.
I am not sure i understood your requirement but you can use the TimeSpan.Compare() method.
var t1 = new TimeSpan(33, 21, 12);
var t2 = new TimeSpan(10, 0, 0);
if (TimeSpan.Compare(t1, t2) > 0)
{
Console.WriteLine(t1.ToString() + " is longer");
}
Edit:
The above code will work fine if the Timespan objects can be created correctly. In case you are working with strings in the format of hh:mm:ss then you will need to split them and call the correct Timespan constructor. Something like below:
public static TimeSpan ConvertStringToTimeStamp(string s)
{
// add checks for input like >0, not null or empty
var split = s.Split(':');
TimeSpan ts;
switch (split.Length)
{
case 3:
ts = new TimeSpan(int.Parse(split[0]), // hours
int.Parse(split[1]), // minutes
int.Parse(split[2])); // seconds // seconds);
break;
case 2:
ts = new TimeSpan(int.Parse(split[0]), // hours
int.Parse(split[1]), // minutes
0); // 0 seconds
break;
case 1:
ts = new TimeSpan(int.Parse(split[0]), // hours
0, // 0 minutes
0); // 0 seconds
break;
default:
throw new Exception("Invalid Input");
}
return ts;
}
I want to parse the following input "10:05" in format "minutes:seconds" in seconds. So 10:05 should be 10 * 60 = 600 + 5 = 605. How can I manage to do this with code ?
Just split the string, parse the numbers, and do your calculation:
string s = "10:05";
var parts = s.Split(':');
int seconds = int.Parse(parts[0]) * 60 + int.Parse(parts[1]);
Console.WriteLine(seconds); // 605
You can also use TimeSpan.Parse in this case which is able to parse this format if you add a hour part in front of it. You can then use the TotalSeconds property to get your desired result:
double seconds = TimeSpan.Parse("00:" + s).TotalSeconds;
Console.WriteLine(seconds); // 605
#poke is close, but you asked for seconds, thus:
string s= "10:05";
double seconds = TimeSpan.Parse("00:" + s).TotalSeconds;
Returns 605.
There are many ways to do this. Here are just a couple. If you know that the format is always going to be mm:ss then you could use the TimeSpan class, the ParseExact method, and the TotalSeconds property. Here's an example of how you could do it.
TimeSpan ts = TimeSpan.ParseExact(mytime, "mm:ss", System.Globalization.CultureInfo.InvariantCulture);
double seconds = ts.TotalSeconds;
If you have a bunch of different formats that can show up you can use the ParseExact and provide multiple time formats. Here's an example that takes a few formats.
//HH -> 24 hour format always with 2 digits ("08" = 8 hours)
// H -> 24 hour format with as few digits as possible ("8" = 8 hours)
//mm -> minutes always with 2 digits ("08" = 8 minutes)
// m -> minutes with as few digits as possible ("8" = 8 minutes)
//ss -> seconds always with 2 digits ("08" = 8 seconds)
// s -> seconds with as few digits as possible ("8" = 8 seconds)
string[] formats = new string["HH:mm:ss", "H:mm:ss", "mm:ss", "m:ss", "ss", "s"];
TimeSpan ts = TimeSpan.ParseExact(mytime, formats, System.Globalization.CultureInfo.InvariantCulture);
double seconds = ts.TotalSeconds;
Here's a link to the MSDN documentation for the TimeSpan class. Check out the Methods and Properties for the TimeSpan class. Here's a link on formatting time strings.
The other way is to manually split the input string into the two parts and use the Convert class to convert each part into integers or doubles.
string[] timeparts = mytime.Split(':');
string minstr = timeparts[0];
string secstr = timeparts[1];
int mins = Convert.ToInt32(minstr);
int secs = Convert.ToInt32(secstr);
int seconds = mins * 60 + secs;
Here's the documentation for the Convert class.
How can I find difference between two time intervals.
Like 13:45:26.836 - 14:24:18.473 which is of the format "Hour:Min:Sec:Millisecs". Now i need to find the time difference between these two times.
How can i do this in C#.?
Thanks in advance.
Basically, what you need to do is put those time values into DateTime structures. Once you have your two DateTime variables, just subtract them from one another - the result is a variable of type TimeSpan:
DateTime dt1 = new DateTime(2010, 5, 7, 13, 45, 26, 836);
DateTime dt2 = new DateTime(2010, 5, 7, 14, 24, 18, 473);
TimeSpan result = dt2 - dt1;
string result2 = result.ToString();
TimeSpan has a ton of properties that get sets - the difference in all sorts of units, e.g. milliseconds, seconds, minutes etc. You can also just do a .ToString() on it to get a string representation of the result. In result2, you'll get something like this:
00:38:51.6370000
Is that what you're looking for?
i'm posting an example;
you can check it and adapt your program,
/* Read the initial time. */
DateTime startTime = DateTime.Now;
Console.WriteLine(startTime);
/* Do something that takes up some time. For example sleep for 1.7 seconds. */
Thread.Sleep(1700);
/* Read the end time. */
DateTime stopTime = DateTime.Now;
Console.WriteLine(stopTime);
/* Compute the duration between the initial and the end time.
* Print out the number of elapsed hours, minutes, seconds and milliseconds. */
TimeSpan duration = stopTime - startTime;
Console.WriteLine("hours:" + duration.Hours);
Console.WriteLine("minutes:" + duration.Minutes);
Console.WriteLine("seconds:" + duration.Seconds);
Console.WriteLine("milliseconds:" + duration.Milliseconds);
Find the number of seconds; subtract both numbers and then you can figure out the time difference. Depending on the programming language you use, I am positive their must be a library that can handle it.
//Start off with a string
string time1s = "13:45:26.836";
string time2s = "14:24:18.473";
TimeSpan interval = DateTime.Parse(time2s) - DateTime.Parse(time1s);
This will produce a result of:
Days 0 int Hours 0 int
Milliseconds 637 int
Minutes 38 int Seconds 51 int
Ticks 23316370000 long
TotalDays 0.02698653935185185 double
TotalHours 0.64767694444444446 double
TotalMilliseconds 2331637.0 double
TotalMinutes 38.860616666666665 double
TotalSeconds 2331.6369999999997 double
I have the input 15:20:30
I want to convert to seconds.
Seeing as though you haven't specified the question properly I have interpreted it to represent 15 hours 20 minutes and 30 seconds, as opposed to DateTime.Now. (Obviously this is the same as "How many seconds since midnight")
TimeSpan MySpan = new TimeSpan(15, 20, 30);
MySpan.TotalSeconds;
Although if you're only wanting the Seconds from the current DateTime.Now (this is not the TotalSeconds, just the current minutes seconds), just use:
DateTime.Now.Second
var dt = DateTime.Now;
var ticks = dt.Ticks;
var seconds = ticks/TimeSpan.TicksPerSecond;
Each tick is 100 nanoseconds.
Not sure what you really want, but if you want to compute the number of seconds from 15 hours, 20 minutes and 30 seconds you can do this:
Int32 GetSeconds(Int32 hours, Int32 minutes, Int32 seconds) {
return ((hours*60) + minutes)*60 + seconds;
}