Getting values from DateTime

  • Thread starter Thread starter John Slate
  • Start date Start date
J

John Slate

I have a situation where users will input a start date and an end date,
then return the number of weekdays only. Is this possible with the
DateTime class?
 
Hi,

Use the calendar control in this way you dont have to worry about the
conversion, if you use something else like a textbox you should convert the
TextBox.Text to a DateTime before any date related operation


cheers,
 
Yes, but what I wanted to know was whether there was a method or
property which would return the number of weekdays, excluding weekends,
from the selected dates...
 
The way you would find that out would be to review the properties and
methods of DateTime in the help file.

--Bob
 
DateTime dt_new;
DateTime dt_start, dt_end;
dt_start = Convert.ToDateTime("10/1/2004");
dt_end = Convert.ToDateTime("10/20/2004");

TimeSpan ts = dt_end - dt_start;
int numberOfDays = ts.Days;

for(int i = 0; i<numberOfDays; i++)
{
dt_new = dt_start.AddDays(i);
if(dt_new.DayOfWeek.ToString()!="Saturday"&&dt_new.DayOfWeek.ToString()!="Sunday")
{
listBox1.Items.Add(dt_new.ToString());
}
}

This will just look through every date between the two dates specified and see whether or not the date is saturday or sunday. If the date is, than it will not put that date in a listbox. I think this is what you are looking for.
I have a situation where users will input a start date and an end date,
then return the number of weekdays only. Is this possible with the
DateTime class

User submitted from AEWNET (http://www.aewnet.com/)
 
It might be better to replace
if(dt_new.DayOfWeek.ToString()!="Saturday"&&dt_new.DayOfWeek.ToString()!="Sunday")
by
if(dt_new.DayOfWeek != DayOfWeek.Saturday && dt_new.DayOfWeek !=
DayOfWeek.Sunday)
because (a) it should be slightly faster, and (b) it doesn't rely on
locale-specific (if that's the right term) day names.

An even faster method could be to work out the number of complete weeks
(basically divide numberOfDays by 7) and multiply that by 5, then do some
adjustments for the partial weeks at the start and end of the date range -
but unless you're dealing with very long time spans it's probably not worth
the effort!

Chris Jobson
 
Hey
Try this ... it worked for me.
<code>
public string DateAdder(string Date,double DayCount)
{
string [] strDate = Date.Split('/');
int Day = Convert.ToInt32(strDate[0]);
int Month = Convert.ToInt32(strDate[1]);
int Year = Convert.ToInt32(strDate[2]);
double one = 1;
double two = 2;
DateTime dt = new DateTime(Year,Month,Day);
DateTime NewDt = dt.AddDays(DayCount);
DateTime FinalDate;
switch(NewDt.DayOfWeek)
{
case DayOfWeek.Saturday:
FinalDate = NewDt.AddDays(two);
break;
case DayOfWeek.Sunday:
FinalDate = NewDt.AddDays(one);
break;
default:
FinalDate = NewDt;
break;
}
string ReturnDate = FinalDate.Day + "/" + FinalDate.Month + "/" +
FinalDate.Year;
return ReturnDate;
</code>

Cheers
Liz
 
Back
Top