Find Previous Friday (Full Version)

All Forums >> [Web Development] >> ASP and Database



Message


ou812 -> Find Previous Friday (4/3/2008 11:50:55)

I need to come up with a function to find the previous Friday's date when a date is entered. So, if a date is entered and it is Wednesday April 2nd, I need to be able to know the previous Friday was March 28th. Has anyone already written something like this, or have some thoughts? I'm not sure how to attack it just yet, but I'm thinking I can just subtract a day, looping backwards from the entered date, and then check the weekday of that date until I hit a Friday. But there has to be a better way. Hmm, and if the date is already Friday, I need to go back to the previous still.

Any thoughts?

Oh, and for this I'm using ASP, but any psuedo code or ideas would be great.




rdouglass -> RE: Find Previous Friday (4/3/2008 12:53:14)

How 'bout something like this?

DateAdd("d",(DatePart("w",myDate)*-1)-2,myDate)

That *should* find the Friday of last week of "myDate" because

(DatePart("w",myDate)*-1)

should return the negative of the day of the week that myDate is. That number should get us back to Sunday.

That make sense? So then just take 2 more days from that.

Today is Thurs. (DatePart("w",myDate)*-1) should return -4. So then just taking 2 more days (making -6) should get us back to Friday.

That close?

EDIT: Saturdays I'm not so sure of. Entering a Saturday will probably take you back a full 8 days but you could always check for that first. If you need to just make sure (DatePart("w",myDate)*-1)-2 is never greater than 7; if it is, subtract 7 and it should set it back.




rdouglass -> RE: Find Previous Friday (4/3/2008 13:03:17)

quote:

If you need to just make sure (DatePart("w",myDate)*-1)-2 is never greater than 7; if it is, subtract 7 and it should set it back.


Actually if you follow the logic, it should read: ...is never less than 7; if it is, add 7....
[8|] [:D]




ou812 -> RE: Find Previous Friday (4/3/2008 13:24:24)

Thanks, Roger! That should work perfect. And makes sense. As you can see I was off on some other tangent in my attempt to get a solution. Your solution is MUCH more elegant. I'll do a bit to handle Saturdays as you pointed out, but again, great solution. Thanks very much. You no doubt saved me some hours.




Page: [1]

Valid CSS!




Forum Software © ASPPlayground.NET Advanced Edition 2.4.5 ANSI
0.15625