startdate / enddate sum

N

nologo

all,
I have a startdate and enddate, i wish to be able to calculate how
many weeks have been selected. so for example, using the startdate and
enddate, i select 11/02/2008 and 25/02/2008 i need a method to sum how
many weeks that is.
Any suggestions?Where do i start?

Cheers!
 
J

Jon Skeet [C# MVP]

nologo said:
I have a startdate and enddate, i wish to be able to calculate how
many weeks have been selected. so for example, using the startdate and
enddate, i select 11/02/2008 and 25/02/2008 i need a method to sum how
many weeks that is.
Any suggestions?Where do i start?

You can subtract one DateTime from another to get a TimeSpan. From that
you can fetch the total number of days (TimeSpan.TotalDays). You'll
need to work out what you want to report for "10.5 days" etc though.
 
M

Marc Gravell

DateTime start = new DateTime(2008,02,11), end = new
DateTime(2008,02,25);
double weeks = end.Subtract(start).TotalDays / 7;

You might want to use Math.Floor() or Math.Ceiling() to round up or down...

Marc
 
N

nologo

            DateTime start = new DateTime(2008,02,11), end = new
DateTime(2008,02,25);
            double weeks = end.Subtract(start).TotalDays / 7;

You might want to use Math.Floor() or Math.Ceiling() to round up or down....

Marc

thanks for your replies! great help.
Marc, could i do the following..
DateTime start = new DateTime(variable name), end = new
DateTime(variable name);
double weeks = end.Subtract(start).TotalDays / 7;
because those dates are selected at the users command. then using
Math.Floor() to round up?
 
M

Marc Gravell

It depends what [variable name] is...
If it is already a DateTime, then just use in place of [start] and [end]
If they are strings, then you'll need to use DateTime.Parse().

Alternatively, give the user a date-picker, and just use the .Value (which
should be a DateTime).

Marc
 
N

nologo

Finished code:

// Convert strings to DateTime
DateTime dtStart = Convert.ToDateTime(udt.strStartDate);
DateTime dtEnd = Convert.ToDateTime(udt.strEndDate);

// Subtracts End Date from Start Date
double weeks = dtEnd.Subtract(dtStart).TotalDays / 7;

// Rounds the value to the closest whole number int
double fvWeeks = Math.Floor((weeks + 0.5));

Regards to Jon Skeet & Marc Gravell
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top