2

I want to get the year but there is no TotalYears in the DateTime so im trying my luck here. what i'm doing is im inputting a date from the form like this

DateTime acquisition = DateTime.Parse(Request.Form["inputAcquisition"]);

Then the date today so it will subtract to the acquisition date.

 DateTime now = DateTime.Now;

Now this is the part that's getting me confused. subtracting them

TimeSpan difference = now - acquisition ;

I'm receiving some value but it's like a gibberish of 2819:012:23123:1246 // not actual data.

How can I just get the total difference of the year? If i Input March 20, 2014, subtract to year today I will get 3 as an output?

WTFZane
  • 592
  • 1
  • 4
  • 25
  • My question is not as complex as the question of that. I just wanna get the year not as `2.2` for 2 years and 73 days – WTFZane Mar 14 '17 at 02:52
  • Check: http://stackoverflow.com/questions/15957984/format-a-timespan-with-years – NoChance Mar 14 '17 at 04:02

2 Answers2

1

TimeSpan has properties that will tell you many ticks have elapsed between two times. You can use .TotalDays to get the number of days that represents. On a Gregorian calendar, that doesn't map nicely to years (you can divide by 365.24 to get the approximate number of years).

You will need to decide what you mean by years. How many times Jan 1 has been crossed between the two dates? The difference in the calendar year (2017 - 2014 = 3)? etc.

Tim
  • 5,940
  • 1
  • 12
  • 18
1

Use as below:

//Option 1 - Just Years only
DateTime current = DateTime.Now;
DateTime d = new DateTime(2014, 2, 20);
int yearDiff = current.Year - d.Year;
Console.WriteLine("Difference in Years: " + yearDiff);

// Option 2 - More precise
long diff = current.Ticks - d.Ticks;
DateTime yearDiff2 = new DateTime(diff);
Console.WriteLine("Difference in Years: " + yearDiff2.Year);

Similar Question: Calculate the difference between two dates and get the value in years?

Community
  • 1
  • 1
RK_Aus
  • 886
  • 1
  • 11
  • 18
  • Hope that you forgot to add the reference to [this](http://stackoverflow.com/questions/3152977/calculate-the-difference-between-two-dates-and-get-the-value-in-years) – sujith karivelil Mar 14 '17 at 02:55
  • I've used the option 1. Is there an issue or trouble if its leap year? – WTFZane Mar 14 '17 at 03:06
  • It doesn't matter for leap year. In the first option, it will consider Years only. In the second option it will consider months, days, hours etc. and give the exact difference in Years. For example, if your input 1-Jan-2014, output of the first option will be 3 (2017 - 2014) and second option will be 4 (as it considers months, days, hours etc.) – RK_Aus Mar 14 '17 at 03:12
  • @RajeshKrishna: You have to read [this](http://stackoverflow.com/help/referencing) as well – sujith karivelil Mar 14 '17 at 03:18
  • Thank you, buddy...I not seen these answers. As you suggested good to add a reference to other answers. – RK_Aus Mar 14 '17 at 03:29