Question

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 !

Était-ce utile?

La solution 3

@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.

Autres conseils

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.

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.

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

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top