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
Related
I have been facing issue on time subtraction in C#.
For example I start timer on 4/5/2017 11:56:27 PM and end the timer in 5/5/2017 12:10:27 AM when I subtract this it shows me result 23 hours.
I want that it show exact time like 14 minutes. I am sharing my code as well.
double rate1 = Convert.ToDouble(rate.Text);
double value = rate1 / 3600;
DateTime dt = DateTime.Parse(text3.Text);
DateTime edt = DateTime.Parse(text5.Text);
var res = dt.Subtract(edt).ToString().Replace('-', ' ');
DateTime tt = Convert.ToDateTime(res);
DateTime dt1 = DateTime.Parse(text4.Text);
DateTime edt1 = DateTime.Parse(text6.Text);
var res1 = dt.Subtract(edt1).ToString().Replace('-', ' ');
double sec = TimeSpan.Parse(res).TotalSeconds;
double sec1 = TimeSpan.Parse(res1).TotalSeconds;
text7.Text = res.ToString();
text8.Text = res1.ToString();
It seems like you're showing a lot of code that's difficult to reproduce for us, and the variable names are not the clearest. I'm assuming dt stands for "datetime", and edt stands for "end datetime". If that's correct, then you're subtracting the end date from the start date instead of the other way around (you should subtract the smaller from the larger).
So, here's how to get the difference between start and end (I'm using Hindi culture info for this):
var dateFormatCulture = new CultureInfo("hi-IN");
var startDate = DateTime.Parse("4/5/2017 11:56:27 PM", dateFormatCulture);
var endDate = DateTime.Parse("5/5/2017 12:10:27 AM", dateFormatCulture);
var difference = endDate.Subtract(startDate);
You say you want "the exact time like 14 minutes". I'm not sure if that means you don't want to show the rest of the values, but here are a few ways you can display it.
Console.WriteLine($"General short string format: {difference:g}");
Console.WriteLine(
"Custom string format: {0} days, {1} hours, {2} minutes, {3} seconds",
difference.Days, difference.Hours, difference.Minutes, difference.Seconds);
Console.WriteLine("In terms of minutes, the total minutes difference is: {0}",
difference.TotalMinutes);
Notice that there's a difference between the second an third example in the methods being called to show the minutes . Minutes will display just the minutes portion of the difference. TotalMinutes will display the entire difference in terms of minutes. In your case they are the same, but if the difference was 1 hour and 14 minutes, Minutes would still be 14, but TotalMinutes would be 74.
The output looks like:
It looks like you might have a copy/paste error. In this line, did you mean to reference dt1 rather than dt?
var res1 = dt.Subtract(edt1).ToString().Replace('-', ' ');
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.
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.
I need format TimeSpan to minutes and seconds(without hours), I looks to MSDN formatting but not found any example which I can reuse.
Example of what I need:
TimeSpan.FromSeconds(1) --> 00:01
TimeSpan.FromSeconds(60) --> 01:00
TimeSpan.FromSeconds(3600) --> 60:00
TimeSpan.FromSeconds(36000) --> 600:00
Any ideas which format possible use to convert TimeSpan to string in minutes:seconds format?
Try this:
var timeSpan = TimeSpan.FromSeconds(3123);
var result = string.Format("{0:D2}:{1:D2}", (int) timeSpan.TotalMinutes, timeSpan.Seconds);
// result = "52:03"
You can use TimeSpan.TotalMinutes for the first part and also pad the number of seconds with a custom format string:
var formatted = string.Format("{0}:{1:D2}", (int)ts.TotalMinutes, ts.Seconds);
For those who prefer to just pass string format
timespan.ToString("mm\\:ss");
This is my input:
55
This is my desired output:
PT55H
Is there a built in class in C# that converts a timespan as: TimeSpan.TryParse(55) or as a string "55" with hours into an ISO8601 formatted string?
You can convert a number to a TimeSpan with the static TimeSpan.FromHours method. For example var ts = TimeSpan.FromHours(55.0);.
If you always want the time represented with hours only, in the ISO system, maybe you can simply say var isostring = String.Format("PT{0}H", ts.TotalHours);.
Coworker just found this for me:
TimeSpan start = new TimeSpan(int.Parse(txtStartHours.Text), 0, 0);
durationNode.Element("StartTime").Value = XmlConvert.ToString(start);
It seems to convert it to PT2D7H, but since I'm using XMLConvert.ToTimeSpan().TotalHours elsewhere, it shouldn't cause any problems!