Link to home
Start Free TrialLog in
Avatar of chkueh
chkuehFlag for Singapore

asked on

How to calculate date using datetimepicker exclude sunday?

Hi, experts

I need to create 1 feature in my program which related to date function.
For example: I have date on 31-March-2010. I need to estimate duration in flexible method such as backward count the date may be for 2days, 3days, 5days, 7days...The date must not including sunday.....

How can i do it?

For 7days may be i can add 1 day extra...because sunday not include...any comment?

Thanks..
Avatar of Nasir Razzaq
Nasir Razzaq
Flag of United Kingdom of Great Britain and Northern Ireland image

I am not sure if this is what you want but give it a try




                Dim sDate, eDate As Date
                Dim dayCount As Integer
                While sDate < eDate
                    If sDate.DayOfWeek <> DayOfWeek.Sunday Then
                        dayCount += 1
                    End If
                    sDate = sDate.AddDays(1)
                End While

Open in new window

lf i understand correctly, u wish to be able to calculate previous date excluding sunday and return the result date?

for example:
if date is March 16th and u want 10 days backward excluding sundays, the result date will be:
March 4th (since there are 2 sundays in this range).

is that correct?
ASKER CERTIFIED SOLUTION
Avatar of Nasir Razzaq
Nasir Razzaq
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of chkueh

ASKER

Hi, sedgwick...your understanding is correct. Thanks CodeCruiser for the code...i had try it and it is works...

my question again....the above code is excluding sunday...how about if excluding saturday and sunday? should i use " sDate = sDate.AddDays(-2) " ?

Thanks.
It would be better to change this section

If sDate.DayOfWeek = DayOfWeek.Sunday Then
                        sDate = sDate.AddDays(-1)
                    End If
 
to
If sDate.DayOfWeek = DayOfWeek.Sunday or sDate.DayOfWeek = DayOfWeek.Saturday Then
                        sDate = sDate.AddDays(-1)
End If
Avatar of chkueh

ASKER

Hi, CodeCruiser...thanks for your code again....the code really work for me.

May i know why should we count it (-1)? Can you explain to me? I really new to this topic. thanks
We loop for the given number of days and keep subtract 1 day to the date for each day. But if its sunday or saturday, we subtract 2 days from the date. So instead of "should i use " sDate = sDate.AddDays(-2)" as you said, i call the adddays(-1) twice!
Avatar of chkueh

ASKER

Ok. I understand. Thanks you for your help.
Avatar of chkueh

ASKER

Fast reply & good answer....Good helper.
Glad to help :-)