Click here to Skip to main content
15,905,323 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am making window application using C#.NET and SQL SERVER.I Have two labels in a form for dates.starting date and ending date with respective datetimepicker control.Now i have third label who computes the duration(difference)between dates.I have tried following code
C#
private void txtduration_MouseClick(object sender, MouseEventArgs e)
      {
          int n;
          if (startingdate.Value > endingdate.Value)
          {
              n = Convert.ToInt32(startingdate.Value - endingdate.Value);
              txtduration.Text = n.ToString();
          }
          else
              n = Convert.ToInt32(endingdate.Value - startingdate.Value);
          txtduration.Text = n.ToString();
}


getting an error
Unable to cast object to type 'System.Timespan' to type System.iconvertible

Please help me regarding this
Thanx in advance
regards
Posted
Updated 9-May-11 17:47pm
v3

1 solution

If you subtract two DateTime data types, then you get a TimeSpan as a result. You are then trying to convert this into an int, which is not possible. Depending on what you are trying to do you need do do this:

C#
int n;
            if (startingdate.Value > endingdate.Value)
            {
                n = (int)(startingdate.Value - endingdate.Value).TotalSeconds;
                //n = (int)(startingdate.Value - endingdate.Value).TotalMinutes;
                //n = (int)(startingdate.Value - endingdate.Value).TotalDays; etc
                txtduration.Text = n.ToString();
            }
            else
                n = (int)(endingdate.Value - startingdate.Value).TotalSeconds;
            txtduration.Text = n.ToString();


This assumes you are trying to find the total duration in one of those formats

Hope this helps
 
Share this answer
 
Comments
CPallini 9-May-11 9:40am    
Why the 'if'? I mean: if you admit ending times to come before starting ones then you have to admit negative durations too, I guess. My 5.
Wayne Gaylard 9-May-11 9:56am    
To be honest I just jimmied the OP's code, didn't really change any logic.
Sergey Alexandrovich Kryukov 9-May-11 22:23pm    
Therefore, my 4.
--SA
shivani 2013 10-May-11 0:40am    
thanx

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900