21

I'm trying to convert timespan variable into an integer variable using 'parse'. I get an error that says:

Format exception was unhandled: Input string was not in correct format

This is the code is have :

   private void dateTimePicker4_ValueChanged(object sender, EventArgs e)
    {
        TimeSpan t = dateTimePicker4.Value.ToLocalTime() - dateTimePicker3.Value.ToLocalTime();
        int x = int.Parse(t.ToString());
        y = x;
    }

My target is to display this the change in time for two timepickers, dynamically in a text box, i.e, the difference in minutes between them should be displayed in a textbox automatically.

Mahmoud Gamal
  • 72,639
  • 16
  • 129
  • 156
Aman Mehrotra
  • 293
  • 2
  • 6
  • 15
  • This in an awful question. Not the question itself, just that you are trying to parse the `ToString` value. You need to get in the habit of looking for existing properties and methods that might already do what you want. More often that not, the functionality usually exists already, somewhere – musefan May 17 '13 at 11:01
  • thanks, will keep that in mind. – Aman Mehrotra May 17 '13 at 11:08

2 Answers2

40

the difference in minutes between them should be displayed in a textbox automatically.

Instead of parsing use TimeSpan.TotalMinutes property.

t.TotalMinutes;

The property is of double type, if you just need to integer part then you can do:

int x = (int) t.totalMinutes;
Habib
  • 205,061
  • 27
  • 376
  • 407
4
 private void dateTimePicker4_ValueChanged(object sender, EventArgs e)
    {
        TimeSpan t = dateTimePicker4.Value.ToLocalTime() - dateTimePicker3.Value.ToLocalTime();
        int x = int.Parse(t.Minutes.ToString());
        y = x;
    }

Have you tried changing it to int x = int.Parse(t.Minutes.ToString());?

From : http://msdn.microsoft.com/en-us/library/system.timespan.aspx

Roman Marusyk
  • 19,402
  • 24
  • 55
  • 90
Lawrence Wong
  • 1,079
  • 2
  • 21
  • 38