Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to achieve timespan to string conversion?

I tried searching here, but it couldn't help me much ..
I want to convert time_span to string, I don't want to return the timespan in days .. but only HH:mm:ss. How to achieve that?

My sample code is here:

              String time_span_par = "06:12:40";
              String time_str = "18:13:59";
              TimeSpan time_span_var = TimeSpan.Parse(time_span_par);
              TimeSpan time_span = TimeSpan.Parse(time_str);

              time_span = time_span.Add(time_span_var);
              string temp = time_span.ToString("HH:mm:ss");
like image 979
InfantPro'Aravind' Avatar asked Mar 05 '10 06:03

InfantPro'Aravind'


People also ask

How do you convert a string to a time?

We can convert a string to datetime using strptime() function. This function is available in datetime and time modules to parse a string to datetime and time objects respectively.

How do I convert DateTime to TimeSpan?

To convert a DateTime to a TimeSpan you should choose a base date/time - e.g. midnight of January 1st, 2000, and subtract it from your DateTime value (and add it when you want to convert back to DateTime ). If you simply want to convert a DateTime to a number you can use the Ticks property. Save this answer.

What format is TimeSpan?

NET Framework 4. "c" is the default TimeSpan format string; the TimeSpan. ToString() method formats a time interval value by using the "c" format string. TimeSpan also supports the "t" and "T" standard format strings, which are identical in behavior to the "c" standard format string.


2 Answers

Try using

DateTime d = new DateTime(time_span.Ticks);
string time = d.ToString("HH:mm:ss");
like image 83
Adriaan Stander Avatar answered Oct 02 '22 21:10

Adriaan Stander


This should work:

string temp = string.Format("{0}:{1}:{2}",
    time_span.Hours.ToString(), time_span.Minutes.ToString(),
    time_span.Seconds.ToString());

As per comment if you want the double digits you could do:

string temp = string.Format("{0}:{1}:{2}",
    time_span.Hours.ToString("00"), time_span.Minutes.ToString("00"),
    time_span.Seconds.ToString("00"));

Edited:as per jimmy's comment,

string temp = string.Format("{0:00}:{1:00}:{2:00}",time_span.Hours, time_span.Minutes, time_span.Seconds);
like image 38
Kelsey Avatar answered Oct 02 '22 19:10

Kelsey