Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. how to get difference between 2 dates in years:months format?

how to get difference between 2 dates in years:months format?

Scheduled Pinned Locked Moved C#
questioncsharphelptutorial
10 Posts 6 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • A Offline
    A Offline
    Anurag Sinha V
    wrote on last edited by
    #1

    Hi all, AM working on a C# project.. my requirement is as follows: there are 2 dates viz date1 & date2. if date1 > date2 the difference should come as e.g (3years,2months) if date1 < date2 the difference should come as e.g (-3years,-2months) I am able to get the first scenario but the second scenario I am having problems with, not able to calculate the number of months in negative quite correctly... Below is the code used in case of positive scenario,currentdate is alwys greater than the assetCapDate passed as a value: public string newmethod(string assetCapDate) { string timeStr = string.Empty; int years = 0; int months = 0; int days = 0; TimeSpan ts = new TimeSpan(); System.DateTime date1 = DateTime.Now; System.DateTime date2 = Convert.ToDateTime(assetCapDate); ts = date1.Subtract(date2); years = (ts.Days/365); do { for(int i=0; i <= 12; i++) { if(date1.Subtract(date2.AddYears(years).AddMonths(i)).Days >=0) { months = i; } else { break; } } if(months > 12) years = years + 1; }while(months > 12); days = date1.Subtract(date2.AddYears(years).AddMonths(months)).Days; if (years > 0) { timeStr += years.ToString() + " Years, "; } if (months > 0) { timeStr += months.ToString() + " Months"; } if (days > 0) { timeStr += days.ToString() + " Days"; } return(timeStr); } Any help would be highly appreciated. I am not sure whether this question falls under C# domain..Moderators please advise accordingly..will move this question to another domain if required.

    Regards Anurag

    L P R T 4 Replies Last reply
    0
    • A Anurag Sinha V

      Hi all, AM working on a C# project.. my requirement is as follows: there are 2 dates viz date1 & date2. if date1 > date2 the difference should come as e.g (3years,2months) if date1 < date2 the difference should come as e.g (-3years,-2months) I am able to get the first scenario but the second scenario I am having problems with, not able to calculate the number of months in negative quite correctly... Below is the code used in case of positive scenario,currentdate is alwys greater than the assetCapDate passed as a value: public string newmethod(string assetCapDate) { string timeStr = string.Empty; int years = 0; int months = 0; int days = 0; TimeSpan ts = new TimeSpan(); System.DateTime date1 = DateTime.Now; System.DateTime date2 = Convert.ToDateTime(assetCapDate); ts = date1.Subtract(date2); years = (ts.Days/365); do { for(int i=0; i <= 12; i++) { if(date1.Subtract(date2.AddYears(years).AddMonths(i)).Days >=0) { months = i; } else { break; } } if(months > 12) years = years + 1; }while(months > 12); days = date1.Subtract(date2.AddYears(years).AddMonths(months)).Days; if (years > 0) { timeStr += years.ToString() + " Years, "; } if (months > 0) { timeStr += months.ToString() + " Months"; } if (days > 0) { timeStr += days.ToString() + " Days"; } return(timeStr); } Any help would be highly appreciated. I am not sure whether this question falls under C# domain..Moderators please advise accordingly..will move this question to another domain if required.

      Regards Anurag

      L Offline
      L Offline
      Lost User
      wrote on last edited by
      #2

      Use the Math.Abs()[^] method to get the absolute value of the difference when converting to years and months.

      One of these days I'm going to think of a really clever signature.

      A 1 Reply Last reply
      0
      • L Lost User

        Use the Math.Abs()[^] method to get the absolute value of the difference when converting to years and months.

        One of these days I'm going to think of a really clever signature.

        A Offline
        A Offline
        Anurag Sinha V
        wrote on last edited by
        #3

        hi Richard..thxx for the suggestion..i did try Math.Abs stuff but still not getting the desired result... The conversion into months in negative scenario is what I am not getting.. Further assistance would be highly appreciated..

        Regards Anurag

        L 1 Reply Last reply
        0
        • A Anurag Sinha V

          Hi all, AM working on a C# project.. my requirement is as follows: there are 2 dates viz date1 & date2. if date1 > date2 the difference should come as e.g (3years,2months) if date1 < date2 the difference should come as e.g (-3years,-2months) I am able to get the first scenario but the second scenario I am having problems with, not able to calculate the number of months in negative quite correctly... Below is the code used in case of positive scenario,currentdate is alwys greater than the assetCapDate passed as a value: public string newmethod(string assetCapDate) { string timeStr = string.Empty; int years = 0; int months = 0; int days = 0; TimeSpan ts = new TimeSpan(); System.DateTime date1 = DateTime.Now; System.DateTime date2 = Convert.ToDateTime(assetCapDate); ts = date1.Subtract(date2); years = (ts.Days/365); do { for(int i=0; i <= 12; i++) { if(date1.Subtract(date2.AddYears(years).AddMonths(i)).Days >=0) { months = i; } else { break; } } if(months > 12) years = years + 1; }while(months > 12); days = date1.Subtract(date2.AddYears(years).AddMonths(months)).Days; if (years > 0) { timeStr += years.ToString() + " Years, "; } if (months > 0) { timeStr += months.ToString() + " Months"; } if (days > 0) { timeStr += days.ToString() + " Days"; } return(timeStr); } Any help would be highly appreciated. I am not sure whether this question falls under C# domain..Moderators please advise accordingly..will move this question to another domain if required.

          Regards Anurag

          P Offline
          P Offline
          PIEBALDconsult
          wrote on last edited by
          #4

          The general way to get the difference between two DateTime values is just to subtract and get a TimeSpan. A TimeSpan only goes as high as Days, not months or years because doing so is rather difficult -- you must take the varying lengths of months and Leap Days and into account. It were easy and reliable, it would be built-in. If you really want to do this, you're on your own. I seem to recall that someone else asked about this a few months back, but a quick search didn't turn it up.

          M 1 Reply Last reply
          0
          • P PIEBALDconsult

            The general way to get the difference between two DateTime values is just to subtract and get a TimeSpan. A TimeSpan only goes as high as Days, not months or years because doing so is rather difficult -- you must take the varying lengths of months and Leap Days and into account. It were easy and reliable, it would be built-in. If you really want to do this, you're on your own. I seem to recall that someone else asked about this a few months back, but a quick search didn't turn it up.

            M Offline
            M Offline
            Marcus_2
            wrote on last edited by
            #5

            PIEBALDconsult wrote:

            you must take the varying lengths of months and Leap Days and into account.

            I'm not saying that it's right, or that anyone should do it, but what about the Datediff function in the Microsoft.VisualBasic namespace? There you'r able to get the difference in months and years without that hassle. But saying that, I've not used that namespace in a C# solution.

            1 Reply Last reply
            0
            • A Anurag Sinha V

              hi Richard..thxx for the suggestion..i did try Math.Abs stuff but still not getting the desired result... The conversion into months in negative scenario is what I am not getting.. Further assistance would be highly appreciated..

              Regards Anurag

              L Offline
              L Offline
              Lost User
              wrote on last edited by
              #6

              anurag3487 wrote:

              The conversion into months in negative scenario is what I am not getting.

              I'm not sure what you mean by this but using a TimeSpan object will get you the number of days difference, and using the Abs() method will get you the number as a positive integer. Converting that into months and years requires some logic which takes into account leap years and the number of days in each month, none of which is impossible, it just requires a little extra thought.

              One of these days I'm going to think of a really clever signature.

              1 Reply Last reply
              0
              • A Anurag Sinha V

                Hi all, AM working on a C# project.. my requirement is as follows: there are 2 dates viz date1 & date2. if date1 > date2 the difference should come as e.g (3years,2months) if date1 < date2 the difference should come as e.g (-3years,-2months) I am able to get the first scenario but the second scenario I am having problems with, not able to calculate the number of months in negative quite correctly... Below is the code used in case of positive scenario,currentdate is alwys greater than the assetCapDate passed as a value: public string newmethod(string assetCapDate) { string timeStr = string.Empty; int years = 0; int months = 0; int days = 0; TimeSpan ts = new TimeSpan(); System.DateTime date1 = DateTime.Now; System.DateTime date2 = Convert.ToDateTime(assetCapDate); ts = date1.Subtract(date2); years = (ts.Days/365); do { for(int i=0; i <= 12; i++) { if(date1.Subtract(date2.AddYears(years).AddMonths(i)).Days >=0) { months = i; } else { break; } } if(months > 12) years = years + 1; }while(months > 12); days = date1.Subtract(date2.AddYears(years).AddMonths(months)).Days; if (years > 0) { timeStr += years.ToString() + " Years, "; } if (months > 0) { timeStr += months.ToString() + " Months"; } if (days > 0) { timeStr += days.ToString() + " Days"; } return(timeStr); } Any help would be highly appreciated. I am not sure whether this question falls under C# domain..Moderators please advise accordingly..will move this question to another domain if required.

                Regards Anurag

                R Offline
                R Offline
                Ravi Bhavnani
                wrote on last edited by
                #7

                See David Morton's answer on this[^] page. /ravi

                My new year resolution: 2048 x 1536 Home | Articles | My .NET bits | Freeware ravib(at)ravib(dot)com

                A 1 Reply Last reply
                0
                • R Ravi Bhavnani

                  See David Morton's answer on this[^] page. /ravi

                  My new year resolution: 2048 x 1536 Home | Articles | My .NET bits | Freeware ravib(at)ravib(dot)com

                  A Offline
                  A Offline
                  Anurag Sinha V
                  wrote on last edited by
                  #8

                  thanks a lot everybody for the responses.. will do evrything what is required to crack it...

                  1 Reply Last reply
                  0
                  • A Anurag Sinha V

                    Hi all, AM working on a C# project.. my requirement is as follows: there are 2 dates viz date1 & date2. if date1 > date2 the difference should come as e.g (3years,2months) if date1 < date2 the difference should come as e.g (-3years,-2months) I am able to get the first scenario but the second scenario I am having problems with, not able to calculate the number of months in negative quite correctly... Below is the code used in case of positive scenario,currentdate is alwys greater than the assetCapDate passed as a value: public string newmethod(string assetCapDate) { string timeStr = string.Empty; int years = 0; int months = 0; int days = 0; TimeSpan ts = new TimeSpan(); System.DateTime date1 = DateTime.Now; System.DateTime date2 = Convert.ToDateTime(assetCapDate); ts = date1.Subtract(date2); years = (ts.Days/365); do { for(int i=0; i <= 12; i++) { if(date1.Subtract(date2.AddYears(years).AddMonths(i)).Days >=0) { months = i; } else { break; } } if(months > 12) years = years + 1; }while(months > 12); days = date1.Subtract(date2.AddYears(years).AddMonths(months)).Days; if (years > 0) { timeStr += years.ToString() + " Years, "; } if (months > 0) { timeStr += months.ToString() + " Months"; } if (days > 0) { timeStr += days.ToString() + " Days"; } return(timeStr); } Any help would be highly appreciated. I am not sure whether this question falls under C# domain..Moderators please advise accordingly..will move this question to another domain if required.

                    Regards Anurag

                    T Offline
                    T Offline
                    timeArrowI
                    wrote on last edited by
                    #9

                    I think code "ts.Days/365" is not right,leap year should be considered

                    A 1 Reply Last reply
                    0
                    • T timeArrowI

                      I think code "ts.Days/365" is not right,leap year should be considered

                      A Offline
                      A Offline
                      Anurag Sinha V
                      wrote on last edited by
                      #10

                      hi all..have found the solution to the problem above posted by me..thxx evryone fr their suggestions..will post the answer sometime...

                      1 Reply Last reply
                      0
                      Reply
                      • Reply as topic
                      Log in to reply
                      • Oldest to Newest
                      • Newest to Oldest
                      • Most Votes


                      • Login

                      • Don't have an account? Register

                      • Login or register to search.
                      • First post
                        Last post
                      0
                      • Categories
                      • Recent
                      • Tags
                      • Popular
                      • World
                      • Users
                      • Groups