Click here to Skip to main content
15,860,859 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello Sir

I have two date like:
dt1=01-Jan-2012<br />
dt2=08-Feb-2012<br />

How I will calculate the date difference that it will show the rest day. Means after completion of the month the rest day part will show, e.g. if d2-d1 then it should be 1 month 7 days, then i will fetch only day means 7 days.

I have done like:
C#
DateTime fromdate = Convert.ToDateTime(txtFromDate.Text.Trim()).Date;
       DateTime todate = Convert.ToDateTime(txtToDate.Text.Trim()).Date;

       TimeSpan tot_days = todate.Subtract(fromdate);
       int days = Convert.ToInt32(tot_days.Days);

but it is showing total days including month.

So help me.

Thanks.
Posted
Updated 6-Jun-12 23:48pm
v2
Comments
VJ Reddy 7-Jun-12 6:24am    
For period less than one month please see my solution (4)
Thank you :)

The Solution 1 given by JF2015 is good when the period between tm1 and tm2 is greater than one month. But when the period is less than one month say tm1=15-Jan-2012 and tm2=08-Feb-2012, it returns Months: 1 Days: -7.

I think the following code can be used for both when the period is more than one month and when the period is less than a month.
C#
DateTime date1 = DateTime.ParseExact("15-Jan-2012","d-MMM-yyyy",
			System.Globalization.CultureInfo.InvariantCulture);
DateTime date2 = DateTime.ParseExact("08-Feb-2012","d-MMM-yyyy",
			System.Globalization.CultureInfo.InvariantCulture);

while(date1.AddMonths(1) < date2){
	date1 = date1.AddMonths(1);
}
int days = date2.Subtract(date1).Days;
Console.WriteLine (days);

//days = 24 
//days = 7 when date1= 01-Jan-2012
 
Share this answer
 
Comments
Maciej Los 7-Jun-12 6:44am    
Good work, my 5!
VJ Reddy 7-Jun-12 10:41am    
Thank you, losmac :)
C#
public void TestFunc()
{
   DateTime tm1 = Convert.ToDateTime("01-Jan-2012");
   DateTime tm2 = Convert.ToDateTime("08-Feb-2012");
   TimeSpan span = tm2 - tm1;
   int mDiff = MonthDifference(tm2, tm1);
   double dDiff = (tm2 - tm1.AddMonths(mDiff)).TotalDays;
   MessageBox.Show("Months: " + mDiff + " Days " + dDiff);
}

public int MonthDifference(DateTime lValue, DateTime rValue)
{
   return (lValue.Month - rValue.Month) + 12 * (lValue.Year - rValue.Year);
}
 
Share this answer
 
v2
Comments
VJ Reddy 7-Jun-12 6:23am    
Good answer when the period is more than one month. 5!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900