C# .NET - Urgent Help...Calculate # of months between two dates
Asked By jason smith
27-Mar-08 12:25 PM
Good Morning folks,
I have two dates. I need to know number of months between these two dates. The dates always start on 1st of every month.
example:
date1: 02/01/2008 , date2: 12/01/2005. how to calculate the # of months between date1 and date2?
thanks
nath
try this!
private static int monthDifference(DateTime startDate, DateTime endDate)
{
int monthsApart = 12 * (startDate.Year - endDate.Year) + startDate.Month - endDate.Month;
return Math.Abs(monthsApart);
}
try this...
public static string DateDiff(DateTime startDate, DateTime endDate)
{
string timeStr = string.Empty;
int yr = 0;
int mth = 0;
int days = 0;
TimeSpan ts = new TimeSpan();
ts = endDate.Subtract(startDate);
yr = (ts.Days/365);
do
{
for(int i=0; i <= 12; i++)
{
if(endDate.Subtract(startDate.AddYears(yr).AddMonths(i)).Days > 0)
{
mth = i;
}
else
{
break;
}
}
if(mth > 12)
yr = yr + 1;
}while(mth > 12);
days = endDate.Subtract(startDate.AddYears(yr).AddMonths(mth)).Days;
if(yr > 0)
timeStr += yr.ToString() + “y”;
if(mth > 0)
timeStr += mth.ToString() + “m”;
if(days > 0)
timeStr += days.ToString() + “d”;
return(timeStr);
}
Sundar!!! you are fabulous...it works brother..thanks a mill
Thanks
Santhsoh,
I want to get the # of months with minimal lines of code. you can't assume there are always 365 days in a year. leap years are 366.
any way. thanks much for the effort
regards
nath
the easiest, smallest and fastes function
public static int NoOfMonth(DateTime d1, DateTime d2)
{
bool lg = false;
DateTime dl = DateTime.MinValue, dg = DateTime.MaxValue;
if (d1 > d2)
{
lg = false;
dg = d1;
dl = d2;
}
else if (d1 < d2)
{
lg = true;
dg = d2;
dl = d1;
}
int no = 0;
while (dl < dg)
{
dl = dl.AddMonths(1);
no++;
}
if (lg) return -no;
else return no;
}
Anytime :-)
Santosh replied to sundar k
It is really fabulous way to calculate the month between two given date. Thank a lot. You have save my many days. Thanks
Daniel replied to Santosh
public void setProjectMonths(DateTime startDate, DateTime endDate)
{
double t = 0.0;
DateTime dt1 = startDate;
DateTime dt2 = endDate;
while (dt1 <= dt2)
{
t += 1.0;
dt1 = dt1.AddMonths(1);
}
this.numProjectMonths = t;
}
john replied to ivan fiamengo
pity you did not properly tested your code.
What if
NoOfMonth(DateTime.Now, DateTime.Now); is called. Yeah, your then trying to add 9999 8 12 months, which results in an ArgumentOutOfRangeexception.......
The answer should be zero.
And what if d1 and d2 differ by only a second. are you going to return 1 month in that case?
Besides, try using normal names for your variables. When the ##!??!! does lg mean?
strange......
Leon replied to jason smith
We've adjusted the example and run a few testcases which all succeed. The result is:
public static int MonthsBetween(this DateTime d1, DateTime d2) {
DateTime lowest;
DateTime highest;
if (d1 > d2)
{
highest = d1;
lowest = d2;
}
else if (d1 < d2)
{
highest = d2;
lowest = d1;
}
else
{
return 0;
}
int months = 0;
while (lowest < highest)
{
months++;
lowest = lowest.AddMonths(1);
if (lowest > highest)
{
months--;
}
}
return Math.Abs(months);
}
If you know of a testcase which failes please let us know.
Leon

get sunday between two dates Try this code: protected void Page_Load( object sender, EventArgs e) { DateTime startDate = new DateTime (2011, 1, 1); DateTime endDate = new DateTime (2011, 1, 20); TimeSpan diff = endDate - startDate; int days = diff.Days; int countSundays = 0; for ( var i = 0; i countSundays); } Try this fucntion this will return you sunday between given two dates. public static bool DoesIncludeSunday ( DateTime startDate , DateTime endDate ) { bool r = false ; TimeSpan testSpan = new TimeSpan ( 6 , 0 , 0 , 0 ); TimeSpan actualSpan = endDate
Type timespan not supported Hello im trying to generate an excel file with gembox using a datatable but i keep getting this error: Type TimeSpan is not supported. Description: An unhandled exception occurred during the execution of the current web about the error and where it originated in the code. Exception Details: System.NotSupportedException: Type TimeSpan is not supported. Source Error: Line 209: ExcelFile ef = new ExcelFile(); Line 210: ExcelWorksheet ws Worksheets.Add("DataSheet"); Line 211: ws.InsertDataTable(dtbl, "A1", true); I just found this workaround: DateTime myDateTime = DateTime.MinValue.AddTicks( myTimeSpan.Ticks ); DataRow[] drs = myDataSet.Tables[0].Select( String.Format( "MyTime = '{0}'", myDateTime ) ); / / The TimeSpan data type is a DateTime in DataSet / / if myTimeSpan is '10:30:00' then myDateTime is '01.01.0001 10 Type AND SQL Type Default Mapping CLR Access Database SQLite Database MySQL Database Oracle Database bool Bit Bit Bit NUMBER(1) byte TinyInt TinyInt TinyInt NUMBER(3) byte[] Binary Binary Binary
provide me the asp.net and c # code for the subject provided. Dhiraj Try this- DateTime startDate = new DateTime(DateTime.Today.Year, 2, 1); / / 1st Feb this year DateTime endDate = new DateTime(DateTime.Today.Year+1, 2, 1).AddDays(-1); / / Last day in January next year Define an Extension Method on DateTime like so: public static class DateTimeExtensions { public static bool IsWorkingDay(this DateTime date) { return date.DayOfWeek ! = DayOfWeek.Saturday && date.DayOfWeek ! = DayOfWeek.Sunday; } } Then, use
no of sunday between two dates how to count no of sunday between two dates DateTime d1 = DateTime .Now; DateTime d2 = DateTime .Now.AddDays(30); int count = 0; for ( DateTime d = d1; d < = d2; d = d.Add(1)) { if (d.DayOfWeek = = DayOfWeek .Sunday) { count++; } } Response Write( "total Sundays = " + count); Try this code: void isSunday() { DateTime startDate = new DateTime (2011, 1, 1); DateTime endDate = new DateTime (2011, 1, 20); TimeSpan diff = endDate - startDate; int days = diff.Days; int
0))) day = 29; return day; } [ / code] [code] int day = CheckDays(start.Year, start.Month, validDay); DateTime validation = new DateTime(start.Year, start.Month, day); / / display result foreach (DateTime date in GetDates(validation, end)) { dt.Rows.Add((date.ToShortDateString())); } [ / code> this code outputs: Valuation you try to assign invalid day (for e.g. day 31 to April 2010) on datetime variable, you will get error something like: ArgumentOutOfRangeException (Year, Month, and Day parameters describe an un-representable DateTime.), So there is no chance to hold 31 in the datetime variable if the day of that month / year doesn't contain 31. Can you post is really easy. There's in built .NET functionality for that. Just use: int days = DateTime.DaysInMonth(int year, int month); so for example to get number of days in Feb, 2010 use: int days = DateTime.DaysInMonth(2010, 2); Hope that helped. Cheers ;) If a validDay = 31, then for e.g