Solved

Formatting TimeSpan in C#

Posted on 2011-03-23
12
875 Views
Last Modified: 2012-06-27
How can I format a Date Difference in C# using timespan.subtract

Here is what I have so far, I need it to return in hh:mi format

If there is an easier way to do it other than timespan im open to it.  I just have to return this to the user in an hh:mi format.  Even (negative times) -hh:mi if the time returned is negative.

Thanks
DateTime startTime = new DateTime(); 
 DateTime endTime = new DateTime();
 TimeSpan conflictDuration = new TimeSpan();

startTime = 03/28/2011 11:45;
endTime =   03/28/2011 1:47;

conflictDuration = endTime.Subtract(startTime);

Open in new window

0
Comment
Question by:jmpatton
  • 6
  • 5
12 Comments
 
LVL 22

Accepted Solution

by:
p_davis earned 500 total points
ID: 35202107
string formatted = endTime.Subtract(startTime).ToString("hh:mm");
0
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 35202302
Unfortunately the TimeSpan() class doesn't accept a format in ToString() so you have to manually extract the values and put them together yourself.  =\

Here's one way:
conflictDuration = endTime.Subtract(startTime);
string formatted = (conflictDuration.TotalMilliseconds < 0 ? "-" : "") + Math.Abs(conflictDuration.Hours).ToString("00") + ":" + Math.Abs(conflictDuration.Minutes).ToString("00");
MessageBox.Show(formatted);

Open in new window

0
 
LVL 22

Expert Comment

by:p_davis
ID: 35202354
poo, i don't know what the heck i was thinking.
0
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 35202378
I've often wondered why they didn't implement a ToString() overload that accepts a format for the TimeSpan...it would make perfect sense to me!  =)
0
 
LVL 22

Expert Comment

by:p_davis
ID: 35202384
it would be hard for a span that was more than a day, i guess?
0
 
LVL 23

Expert Comment

by:wdosanjos
ID: 35202887
BTW, TimeSpan.ToString(format) is available in .NET 4:

    http://msdn.microsoft.com/en-us/library/dd992632.aspx

So, p_davis' answer is correct as long as it's .NET 4.

I hope this helps.
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 35203144
Woohoo!  Thanks for update wdosanjos.  =)

You have to escape the ":" though like this:
Dim dtA As DateTime = DateTime.Now
        Dim dtB As DateTime = dtA.AddDays(Math.PI)
        Dim ts As TimeSpan = dtB.Subtract(dtA)
        Label1.Text = ts.ToString("dd\:hh\:mm\:ss")

Open in new window


*This is different than the DateTime.ToString() method which is perfectly happy accepting an un-escaped colon!
0
 
LVL 22

Expert Comment

by:p_davis
ID: 35203166
what is this dim you speak of??? ;p
0
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 35203187
Hahaha...grrrr....I'm always forgetting what ZONE I'm in!  =)

In not as beautiful as VB.Net, the C# equivalent would be:   *wink*
private void button1_Click(object sender, EventArgs e)
        {
            DateTime dtA = DateTime.Now;
            DateTime dtB = dtA.AddDays(Math.PI);
            TimeSpan ts = dtB.Subtract(dtA);
            label1.Text = ts.ToString(@"dd\:hh\:mm\:ss");
        }

Open in new window

0
 
LVL 22

Expert Comment

by:p_davis
ID: 35203203
well defined space of a function embraced by beautiful curly brackets.....all is right with the world
0
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 35203217
// no comment;
0
 
LVL 22

Expert Comment

by:p_davis
ID: 35203963

code puns =)

don't hate!
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In order to hide the "ugly" records selectors (triangles) in the rowheaders, here are some suggestions. Microsoft doesn't have a direct method/property to do it. You can only hide the rowheader column. First solution, the easy way The first sol…
Performance in games development is paramount: every microsecond counts to be able to do everything in less than 33ms (aiming at 16ms). C# foreach statement is one of the worst performance killers, and here I explain why.
Windows 10 is mostly good. However the one thing that annoys me is how many clicks you have to do to dial a VPN connection. You have to go to settings from the start menu, (2 clicks), Network and Internet (1 click), Click VPN (another click) then fi…
Internet Business Fax to Email Made Easy - With  eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, f…

861 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

24 Experts available now in Live!

Get 1:1 Help Now