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.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Iftikar HussainPosted Jul 25, 2013, 1:47 PM
Try like this
Regards,
Iftikar
Ravi ShekharPosted Jul 25, 2013, 11:58 PM
Iftikar HussainPosted Jul 25, 2013, 10:22 PM
Regards,
Iftikar
SUNIL GUTTAPosted Jul 25, 2013, 2:38 PM
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
Sanjeeb LenkaPosted Jul 25, 2013, 2:32 PM
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();
}
}
}
VulpesPosted Jul 25, 2013, 2:05 PM
http://www.c-sharpcorner.com/uploadfile/b942f9/extending-the-datetime-structure-in-C-Sharp-part-ii/