how to change timespan variable to a integer type?

Aman Mehrotra picture Aman Mehrotra · May 17, 2013 · Viewed 69.9k times · Source

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.

Answer

Habib picture Habib · May 17, 2013

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;