how to calculate difference between dates i.e 15-12-1989 & 06-02-2003 .. well i want like difference of days , months , years :) can it be done ??
TY
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Iftikar HussainRank #423 · 5.9K reputationPosted Jul 25, 2013, 9:47 AM EDT
Try like this
Regards,
Iftikar
VulpesRank #55 · 29.2K reputationPosted Jul 25, 2013, 10:05 AM EDT
http://www.c-sharpcorner.com/uploadfile/b942f9/extending-the-datetime-structure-in-C-Sharp-part-ii/
Sanjeeb LenkaRank #301 · 8.3K reputationPosted Jul 25, 2013, 10:32 AM EDT
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace dotnetperl
{
class Class2
{
public static void GetDifference(DateTime date1, DateTime date2)
{
//assumes date2 is the bigger date for simplicity
//years
int Years;
int Months;
int Weeks;
int Days;
TimeSpan diff = date2 - date1;
Years = diff.Days / 366;
DateTime workingDate = date1.AddYears(Years);
while (workingDate.AddYears(1) <= date2)
{
workingDate = workingDate.AddYears(1);
Years++;
}
//months
diff = date2 - workingDate;
Months = diff.Days / 31;
workingDate = workingDate.AddMonths(Months);
while (workingDate.AddMonths(1) <= date2)
{
workingDate = workingDate.AddMonths(1);
Months++;
}
//weeks and days
diff = date2 - workingDate;
Weeks = diff.Days / 7; //weeks always have 7 days
Days = diff.Days % 7;
Console.WriteLine("Years:"+Years);
Console.WriteLine("month:" + Months);
Console.WriteLine("week:" + Weeks);
Console.WriteLine("days:" + Days);
}
static void Main(string[] args)
{
//date in mm/dd/yyyy format
DateTime dt1 = DateTime.Parse("09/12/1989");
DateTime dt2 = DateTime.Parse("06/02/2003");
GetDifference(dt1, dt2);
Console.ReadLine();
}
}
}
SUNIL GUTTARank #1,832 · 810 reputationPosted Jul 25, 2013, 10:38 AM EDT
In between Iftikar Hussain urs solution is very helpful but when i am removing
DateTime zeroTime = new DateTime(1, 1, 1); & int years=(zeroTime+span).year -1
and replacing with simple equation like
int years = dt2.Year - dt1.Year;
I am getting same output ..
i just wanna confirm is both same ?? else any added adv there ???
TY friend
Iftikar HussainRank #423 · 5.9K reputationPosted Jul 25, 2013, 6:22 PM EDT
Regards,
Iftikar
Ravi ShekharRank #673 · 3.6K reputationPosted Jul 25, 2013, 7:58 PM EDT