TimeSpan formatting to minutes ans seconds without hours - c#

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");

Related

Convert time in string format into time format

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

Add time duration to date using addHours() in c#

I want to add time duration to my datetime variable. I am reading the duration from a csv file. The format of duration is 0:29:40 or 1:29:40. When i add this to datetime variable it gives exception of incorrect format. How can I add the duration using this format. Previously I had duration as a simple integer like "6" or "7" but now the format is this "0:29:40" I don't know how to change my code to accommodate this format.
Previously i was doing this
double hours = Convert.ToDouble(row.Cells[2].Value.ToString());
DateTime newdate = finaldate.AddHours(hours);
row.Cells[2].Value.ToString() reads the value from csv
Any help is appreciated, Thanks
You don't need to parse to a double. Parse to a TimeSpan. Something like:
var source = "0:29:40";
var ts = TimeSpan.Parse(source);
Now ts is your time span. And the nice thing with TimeSpan is you can just add it to a DateTime:
DateTime newdate = finaldate + ts;
You are going to need to use the TimeSpan.Parse() or TimeSpan.ParseExact() method to properly parse your string and then simply add that TimeSpan result to your existing date:
var time = TimeSpan.Parse(row.Cells[2].Value.ToString());
DateTime newDate = finalDate.Add(time);
If you need to explicitly specify what each of the values of your time represent, then the TimeSpan.ParseExact() method will allow you to provide a formatting string to specify this:
// This will assume that 1:29:40 is hours, minutes, and seconds
var time = TimeSpan.ParseExact(row.Cells[2].Value.ToString(), #"h\:m\:s", null);

Displaying a formatted TimeSpan as string

I'd like to display a TimeSpan value, formatted as mm:ss (minutes, seconds).
The code currently performs this like this:
var timeSpan = GetTimeUntilNextEvent();
var str = DateTime.MinValue.Add(timeSpan).ToString(#"mm\:ss");
I wonder whether that is correct code. I saw other samples that show this technique, but I am not really sure what is the reason for adding something to the MinValue of DateTime.
Why cannot this code be used ? It seems to product a valid result.
var str = DateTime.FromBinary(0).Add(timeSpan).ToString(#"mm\:ss");
You don't need DateTime to format a TimeSpan.
You could simply use the timespan ToString() method:
TimeSpan timeSpan = new TimeSpan(5, 12, 2);
String str = timeSpan.ToString(#"mm\:ss"));
Also see Link.

Convert TimeSpan from format "hh:mm:ss" to "hh:mm"

I want to show in a TextBox only hour and minutes
var test = dataRow.Field<TimeSpan>("fstart").ToString();
//test ="08:00:00"
var tb = (TextBox) gridViewRow.Cells[2].FindControl("fstart");
tb.Text = test;
how to show only hours and minutes "hh.mm"
You need to convert your data to TimeSpan and then use format:"hh\:mm"
string test ="08:00:00";
TimeSpan ts = TimeSpan.Parse(test);
Console.Write(ts.ToString(#"hh\:mm"));
In your case:
var test = dataRow.Field<TimeSpan>("fstart").ToString(#"hh\:mm"));
Remember to escape the colon :
You may see: Custom TimeSpan Format Strings
There is no need to convert from hh.mm.ss to hh.mm. TimeSpan is stored as a number of ticks (1 tick == 100 nanoseconds) and has no inherent format. What you have to do, is to convert the TimeSpan into a human readable string! This involves formatting. If you do not specify a format explicitly, a default format will be used. In this case hh.mm.ss.
string formatted = timespan.ToString(#"hh\.mm");
Note: This overload of ToString exists since .NET 4.0. It does not support date and time placeholder separator symbols! Therefore you must include them as (escaped) string literals.
The usual way of formatting strings seems not to work for some odd reason (tested with .NET 3.5). (It does not make any difference whether you escape the separator symbol or not):
var timespan = TimeSpan.FromSeconds(1234);
string formatted = String.Format(#"{0:hh\.mm}", timespan); // ==> 00:20:34
However, you can construct the string like this
string formatted =
String.Format("{0:00}.{1:00}", Math.Floor(timespan.TotalHours), timespan.Minutes);
or starting with VS2015 / C# 6.0, using string interpolation:
string formatted = $#"{timespan:hh\:mm}";
You can use TimeSpan methods:
ToString("hh':'mm")
// or
ToString(#"hh\:mm")
Also check all available formats here http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
var test = dataRow.Field<TimeSpan>("fstart").ToString("hh.mm");
//test ="08:00"
var tb = (TextBox) gridViewRow.Cells[2].FindControl("fstart");
tb.Text = test;
I know this is a very old question. If anyone wants to show single-digit hours when your hours are a single digit then you can use
var hoursWithMinutes = TimeSpan.FromHours(hours).ToString(#"h\:mm")
This way, when your hours are double-digit I mean greater than 9 then it will be showing 10:00 something like that.
The previous solutions don't run if hours>24, try this solution if you have time in minutes very big
int minutes = 159000;
TimeSpan t = new TimeSpan(0, minutes, 0);
String HOURS = Math.Round(t.TotalHours, 0).ToString();
if (HOURS.Length==1)
{
HOURS = "0"+HOURS;
}
String MINUTES = t.Minutes.ToString();
if (MINUTES.Length == 1)
{
MINUTES = "0" + MINUTES;
}
String RESULT = HOURS + ":" + MINUTES;
You can achieve this by:
var hhmm = TimeSpan.FromMinutes(minutes).ToString(#"hh\:mm")

How can I convert string to time object for calculation

how do I format output in seconds:milliseconds format?
TimeSpan start = TimeSpan.Parse(pair.Value[3]);
TimeSpan end = TimeSpan.Parse(pair.Value[4]);
Console.WriteLine(TimeSpan.Compare( start,end));
The code here is printing the difference in seconds. how can i fix it using string.format as i dont know the convention for milliseconds?
You need to look at the difference between the two timespans.
TimeSpan start = new TimeSpan(42); // 42 ticks
TimeSpan end = new TimeSpan(420000000);
TimeSpan diff = end.Subtract(start);
string ms = diff.Milliseconds.ToString();
string sec = ((int)diff.TotalSeconds).ToString();
Console.WriteLine(sec + ":" + ms);
How about
Console.WriteLine(end.Subtract(start).TotalMilliseconds)
If it's in seconds, you could just multiply the answer by 1000 and write that out as a string?
Otherwise, take a look at this MSDN article http://msdn.microsoft.com/en-us/library/bb882581.aspx

Categories

Resources