You must Sign In to post a response.
  • Category: .NET

    date difference

    The forum thread has not been reviewed by Editors yet. Readers are advised to use their best judgement before accessing this thread.
    This thread will be reviewed shortly.
    If you think this thread contain inappropriate content, please report to webmaster.
    I am working in C#.net
    we have used code to find month difference between 2 dates
    but when we give dates as
    Date1=4/7/2006
    Date2=4/7/2007
    it is not showing ans as 12 but showing 0 as answer.
    why ?
    Give me proper coding

    DateTime date1=DtWarrantyEndDate;
    DateTime date2=DtAMCEndDate;
    long diff=date2.Ticks-date1.Ticks;
    DateTime difTime = new DateTime( Math.Abs( diff) );
    int Months = difTime.Month;
    txtAMCDuration.Text=Convert.ToString(Months-1);
  • #41082
    For this you have to find the date difference in months then only you will get as 12 months. if try to find the difference between months i will say 0 only. because it will chk diff for months alone and it will not chk the year.
    Thanks
    Vivek

  • #41098
    Hi
    Little bit complicated just think this senerio jan 1 to feb 15 of the same year what will be the result? 1 month or 2?

    try like this


    DateTime first=Convert.ToDateTime("4/7/2007");
    DateTime second=Convert.ToDateTime("4/7/2006");
    TimeSpan diff=first.Subtract(second);
    int totalMonths=(int)diff.TotalDays/30; //I have conside 30 days a months
    Response.Write(totalMonths.ToString());


    Pankaj

  • #41101
    Hi
    Little bit complicated just think this Scenario jan 1 to feb 15 of the same year what will be the result? 1 month or 2?

    try like this

    DateTime first=Convert.ToDateTime("4/7/2007");
    DateTime second=Convert.ToDateTime("4/7/2006");
    TimeSpan diff=first.Subtract(second);
    int totalMonths=(int)diff.TotalDays/30; //I have consider 30 days a month
    Response.Write(totalMonths.ToString());


    Pankaj

    Regards,
    Pankaj

  • #53920
    Off the top of my head I can think of

    (date2.Month - date1.Month) + (12* (date2.Year - date1.Year))


    Maybe that will work for you.

  • #186983
    Steven,

    what will be answer for date1:30/1/2007 and date2:1/2/2007

    :)

  • #186987
    Majid,

    It will give 1. (2-1) +(12*0)
    This is because it counts the number of month boundaries, which is what I interpreted the original question to be about. If you think it should be 0 because there the dates are actually only 2 days apart, then you are asking a different question. In that case, you actually want to know how many days apart the two dates are, and then see how many month sized groups that makes. The problem with this is that a month is not a consistant number of days( it will either be 28,29,30 or 31) and then you have to make an assumption like Pankaj did.

  • #187300
    Check out this code snippet and let me know is it based on some assumption. Yes just one and that is the time part you can ignore time part if you like based on requirements

    private int CalculateTotalMonths(DateTime d1, DateTime d2)
    {
    int totalMonths = 0;
    if (d1.Year != d2.Year)
    {
    totalMonths = d2.Month - d1.Month + (12 * (d2.Year - d1.Year));
    }
    else
    {
    d1 = new DateTime(d1.Year, d1.Month, d1.Day, d1.Hour, d1.Minute, d1.Second);
    d2 = new DateTime(d2.Year, d2.Month, d2.Day, d2.Hour, d2.Minute, d2.Second);
    d1 = d1.AddMonths(1);
    TimeSpan span = d2 - d1;
    while (span.TotalDays >= 0)
    {
    totalMonths++;
    d1 = d1.AddMonths(1);
    span = d2 - d1;
    }
    }
    return (totalMonths);
    }


    cheers :):)

  • #187569
    What is the result that you actually want? Because each one of the methods will give different results (in specific situations) you need to determine what your program requires and use that method. The code that you suggest is perfectly fine, if the totalMonths value is ends up being set to the value that you expect. I find it unusual that you would mix two month counting algorithms based on whether or not the year is the same. And I suspect there are some cases you didn't consider. Check out these examples:
    Nov 30, 2007; Dec 1, 2007 == 0 ;expected
    Nov 1, 2007; Dec 1, 2007 == 1 ;expected
    Dec 30, 2007; Jan 1, 2008 == 1 ;maybe unexpected
    Nov 30, 2007; Dec 1, 2008 == 13 ;maybe unxepected
    Nov 1, 2007; Dec 1, 2008 == 13 ; expected

    if you really want to count the number of full months, it seems as if you are on the right track, but I think it would be better to do:

    private int CalculateTotalMonths(DateTime d1, DateTime d2)
    {
    int totalMonths = 0;
    d1 = d1.AddMonths(1);
    while (d1 <= d2){
    totalMonths++;
    d1 = d1.AddMonths(1);
    }
    return totalMonths;
    }

    Of course, this is a lot slower than just counting the month boundaries, especially for very large date differences. However, you could try this:
    private static int CalculateTotalMonths(DateTime d1,DateTime d2)
    {
    return d2.Month - d1.Month + (12 * (d2.Year - d1.Year)) - ((d2.Day < d1.Day) ? 1 : 0);
    }

    (I am not 100% sure that this works in all cases, but it works in those examples above, and it just as fast for any date difference)

    Steven

  • #187573
    I think it doesn't work for d1: 28/1/2007 d2:1/2/2007 isn't it? I don't need 1 month result in this case.

    All I need is total months between two dates thats it.
    The example could be, monthly profit calculations. If I have to calculate profit between two dates, I need to know how many months difference is there and based on totalmonths I do calculate profit.


    I think the code I posted is not valid for all cases so I need to remove if condition in case when two years are not equal. Rest is fine. So in my scenario it will be all correct if I stick with this code:

    int TotalMonths(DateTime d1, DateTime d2)
    {
    int totalMonths = 0;
    d1 = new DateTime(d1.Year, d1.Month, d1.Day, d1.Hour, d1.Minute, d1.Second);
    d2 = new DateTime(d2.Year, d2.Month, d2.Day, d2.Hour, d2.Minute, d2.Second);
    d1 = d1.AddMonths(1);
    while (d1 <= d2)
    {
    totalMonths++;
    d1 = d1.AddMonths(1);
    }
    return (totalMonths);
    }

    I am recreating datetime instances to avoid the milliseconds messing. I hope this code will work fine in all scanerios.


    Thanks for rectification Steve :).

  • #187574
    I think it doesn't work for d1: 28/1/2007 d2:1/2/2007 isn't it? I don't need 1 month result in this case.

    All I need is total months between two dates thats it.
    The example could be, monthly profit calculations. If I have to calculate profit between two dates, I need to know how many months difference is there and based on totalmonths I do calculate profit.


    I think the code I posted is not valid for all cases so I need to remove if condition in case when two years are not equal. Rest is fine. So in my scenario it will be all correct if I stick with this code:

    int TotalMonths(DateTime d1, DateTime d2)
    {
    int totalMonths = 0;
    d1 = new DateTime(d1.Year, d1.Month, d1.Day, d1.Hour, d1.Minute, d1.Second);
    d2 = new DateTime(d2.Year, d2.Month, d2.Day, d2.Hour, d2.Minute, d2.Second);
    d1 = d1.AddMonths(1);
    while (d1 <= d2)
    {
    totalMonths++;
    d1 = d1.AddMonths(1);
    }
    return (totalMonths);
    }

    I am recreating datetime instances to avoid the milliseconds messing. I hope this code will work fine in all scanerios.


    Thanks for rectification Steve :).

  • #187576
    --edit-- It appears as if this isn't showing up in the correct order, this one should be below

    My newest example was:
    d2.Month - d1.Month + (12 * (d2.Year - d1.Year)) - ((d2.Day < d1.Day) ? 1 : 0);

    ==
    2-1 + (12* (2007 - 2007)) - (1 < 28)?1:0
    ==
    1 + 0 - 1
    ==
    0

    so I think it actually does work for that example

    However, even if you don't want to use this method (I am fine with that :), you can get only the date part of the date by:

    d1 = d1.Date;
    d2 = d2.Date;

    it is slightly more efficient than creating a new date by the parts of the dates (although, I really don't know if it would be noticable).

    Steven

  • #187577
    I thought of a way in which my algorithm doesn't work, and that is if d1 is greater than d2.

    you could always correct for that by swaping the two dates if d1 is > d2

    your algorithm would also exibit this problem.

    Steven

  • #187817
    thats all fine mate, your formula is more appealing to me now so I am sticking with that :). The reason I am recreating a date part to avoid the milliseconds though I do need time part.

    Thanks,

    Majid


This thread is locked for new responses. Please post your comments and questions as a separate thread.
If required, refer to the URL of this page in your new post.