Get time span value in hh:mm format to a string variable

2.3k views Asked by At
DateTime date1 = Convert.ToDateTime('2015/06/20');
DateTime date2= Convert.ToDateTime('2015/05/20');
TimeSpan latetime = date1.Subtract(date2);//here in 'hh:mm:ss' format
string value=latetime.ToString();

I get value as in hh:mm:ss format.But I want to get it only hh:mm format

3

There are 3 answers

0
Soner Gönül On

First of all, your code won't even compile. You need to use double quotes for strings, not single quotes.

DateTime date1 = Convert.ToDateTime("2015/06/20");
DateTime date2 = Convert.ToDateTime("2015/05/20");

By the way, what you see (as a format) on TimeSpan latetime = date1.Subtract(date2); line is probably just a debugger representation. A TimeSpan doesn't have any implicit format itself. Formatting concept only will be an issue when you try get it's textual representation.

And TimeSpan formatting is little bit different than DateTime formatting. You can use hh\\:mm format like;

string value = latetime.ToString("hh\\:mm");

or you can use verbatim string literal;

string value = latetime.ToString(@"hh\:mm");
0
Mohammad Arshad Alam On
string value=latetime.ToString("hh\\:mm");

but result will be 00:00 if you need days then :

string value=latetime.ToString("dd\\:hh\\:mm");

MSDN - Custom TimeSpan

2
Gustav On

What you request could likely be a total hour:minute formatted string:

string value=((int)latetime.TotalHours).ToString() + ":" + latetime.ToString("mm");

This will return: 744:00