Click here to Skip to main content
15,892,809 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)
See more:
C#
TimeSpan ts;
Single nomonths;
ts=startDate.Substract(endDate);
nomonths = Convert.toSingle(ts.days/30);  //ts.days=57


So in nomonths has to get 1.9 but it is showing 1

Please help me.
Posted
Updated 16-Feb-11 6:08am
v3

No!

double nomonths = Convert.TotalDays / 30d;


Read System.TimeSpan help properly (http://msdn.microsoft.com/en-us/library/system.timespan.aspx[^]). Properties not prefixed with "Total" return integer value, but you need floating point.

Your problem was: division integer by integer gives you integer value converted to single. The fractional part was cut even before calling Convert function (which is totally redundant).

—SA
 
Share this answer
 
v3
This is a very basic programming error. Assuming you are a beginner I've choosen a special app name
for my example...

Read about implicit and explicit casting, basic datatypes and precision. These are topics you come across in every programming language - you have to know it!

using System;
namespace ReadChapterOneOfAnyNETBook
{
    class Program
    {
        static void Main(string[] args)
        {            
            DateTime startDate = DateTime.Now.AddDays(-57d);
            DateTime endDate = DateTime.Now;
            TimeSpan ts = endDate - startDate;
            float numberOfMonths = (float) ts.TotalDays / 30f;
            Console.WriteLine(numberOfMonths);
            Console.ReadKey();
        }
    }
}
 
Share this answer
 

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