0

Subtraction two time format ,

string _time_One = "08:30" ;
string _time_Two = "08:35" ;

string _timeInterval = ( DateTime.Parse(_time_One) - DateTime.Parse(_time_Two) ).Minutes.ToString();

It give me the result 5 , but I want to show likes this format 00:05.
Kindly show me how to format it . Thanks in advance !

zey
  • 5,939
  • 14
  • 56
  • 110
  • Kindly show that you understand the problem and what you have tried to resolve it. See [MSDN: TimeSpan.ToString()](http://msdn.microsoft.com/en-us/library/dd992632(v=vs.110).aspx). – CodeCaster Oct 30 '13 at 11:03
  • possible duplicate of [Parse C# string to DateTime](http://stackoverflow.com/questions/7580809/parse-c-sharp-string-to-datetime) – Stephane Delcroix Oct 30 '13 at 11:04
  • possible duplicate of [How do I convert a TimeSpan to a formatted string?](http://stackoverflow.com/questions/842057/how-do-i-convert-a-timespan-to-a-formatted-string) – CodeCaster Oct 30 '13 at 11:05

4 Answers4

4

Subtracting two DateTime gives you a TimeSpan which has it's own formatting support using the ToString method.

For example:

DateTime now = DateTime.Now;
DateTime later = now.AddMinutes(10);
TimeSpan span = later - now;

string result = span.ToString(@"hh\:mm");

You can read more here on MSDN.

Lloyd
  • 29,197
  • 4
  • 84
  • 98
2

Try this:

string _time_One = "08:30";
string _time_Two = "08:35";
var span = (DateTime.Parse(_time_One) - DateTime.Parse(_time_Two));
string _timeInterval = string.Format("{0:hh\\:mm}", span);

For reference: Custom TimeSpan Format Strings.

Alex Filipovici
  • 31,789
  • 6
  • 54
  • 78
1

@Lloyd is right here, but to clarify this for your case:

string _time_One = "08:30" ;
string _time_Two = "08:35" ;

TimeSpan ts = DateTime.Parse(_time_One) - DateTime.Parse(_time_Two);
MessageBox.Show(String.Format("Time: {0:00}:{1:00}", ts.Hours, ts.Minutes));

I hope this helps.

MoonKnight
  • 23,214
  • 40
  • 145
  • 277
0
string _time_One = "08:30";
string _time_Two = "08:35";

string _timeInterval = (DateTime.Parse(_time_One) - DateTime.Parse(_time_Two)).Duration().ToString();

result=>00:05:00

roozbeh
  • 304
  • 1
  • 2
  • 10