Dates in C#

iebidan

Well-known member
Joined
Feb 6, 2003
Messages
484
Well, Im trying to create a function to dispaly how many months - days have passed since a project started, I can know the days, but how can I know how many months????
Here is the code to get the days

C#:
DateTime Uno = new DateTime(2004,01,01);
			DateTime Dos = new DateTime(2004,02,12);

			TimeSpan xx = Dos - Uno;
			double yy = xx.Days;

this returns 42 days, but I need something that returns 1 month 12 days, is there a way to do this, or does anyone has any ideas???
 
What determines what a "month" is? If the starting and
ending dates were both in the middle of a month, theres no way
to determine what "month" passed, if any at all.

If "Uno" is always going to be the start of a month, then just
subtract the difference in the months, add the difference of
the years multiplied by twleve (to account for different years),
then add in the days.

So, in summary, with all the assumptions made above (pseudo-code):
Months = Dos.Months - Uno.Months + (12 * (Dos.Year - Uno.Year))
Days = Dos.Days

Or, if you want to assume that a "month" is always 30 days
(which youve done here, even though January has 31 days),
just do:
Months = xx.Days \ 30
Days = xx.Days Mod 30
 
Well, I think Ill have to create a whole function for this task, there is no simple way to do it, cause if the start day is not the same as the ending day you dont get an exact calc.
Ill let u know how I solved this :D
 
Heres some VB.NET code that does the job:

Code:
Dim StartDate As New DateTime(2004, 2, 13)
Dim EndDate As DateTime = Date.Today
Dim CountMonths As Integer
Dim CountDays As Integer

While StartDate.AddMonths(CountMonths + 1) <= EndDate
   CountMonths += 1
End While

While StartDate.AddMonths(CountMonths).AddDays(CountDays + 1) <= EndDate
   CountDays += 1
End While

MessageBox.Show(CountMonths.ToString & " months, " & CountDays.ToString & " days.")
 
PERFECT!!!! this code works great, now here is the C# version of it. THANK YOU TechnoTone.

C#:
DateTime StartDate =new DateTime(2003, 1, 28);
DateTime EndDate = new DateTime(2004,1,31);
int CountMonths=0;
int CountDays=0;

while (StartDate.AddMonths(CountMonths +1) <= EndDate)
{
      CountMonths +=1;
}

while (StartDate.AddMonths(CountMonths).AddDays(CountDays +1) <= EndDate)
{
     CountDays +=1;
}
MessageBox.Show(CountMonths.ToString() + " months, " + CountDays.ToString() + " days.");
 
Back
Top