How Can I Determine Which Day of the Year a Date Falls On?
Hey, Scripting Guy! How can I determine which day of the year a date falls on? For example, March 2, 2006 is the 61st day of the year.
Hey, TW. You know, we almost feel guilty about answering this question. Why? Well, after all, we can answer it by writing just one line of code:
Wscript.Echo DatePart(“y”, “3/2/2006”)
Note. So if it’s that easy why do we almost feel guilty about answering the question; why don’t we actually feel guilty? Well, to be honest, we believe the Scripting Guys deserve a break once in awhile. After all, look at a typical Scripting Guys day: we might have to write a Scripting Week song or put together a crossword puzzle; for that matter, we might be forced to play around with Microsoft Agent or Windows Media Player. This is obviously arduous and back-breaking work, and yet we do it day in and day out. (Well, except for the extended vacation time we all just finished taking.) You see what we have to go through on a daily basis; surely you can cut us some slack every now and then?
As far as determining the day of the year for a particular date, well, needless to say that doesn’t require much effort: we simply call the DatePart function and pass it two parameters:
“y”, which tells DatePart that we want to know the day of the year.
“3/2/2006”, which tells DatePart which date we need information for.
That’s all we have to do. In turn, DatePart calculates the day of the year and the script echoes the value – 61 – back to us.
What’s cool about DatePart is that it can retrieve other date-related information besides day of the year. For example, want to know the week of the year that 3/2/2006 falls in? Here you go:
Wscript.Echo DatePart(“ww”, “3/2/2006”)
In this case DatePart returns a 9, meaning that 3/2/2006 falls in the ninth week of 2006. How about the quarter:
Wscript.Echo DatePart(“q”, “3/2/2006”)
Did someone ask what day of the week 3/2/2006 falls on? Here’s a script that can help you with that:
intDay = DatePart(“w”, “3/2/2006”)
Select Case intDay
Note. If you can’t stand the suspense any longer, 3/2/2006 falls on a Thursday.
Here’s a complete list of all the different date parts that DatePart can return:
Day of the year
Day of the week
Week of the year
And now, if you’ll excuse us, we have another grueling day to try and get through. Should we have filet mignon again at lunch, or should we try something new today? It’s a tough job, but someone has to do it.
Note. Please don’t point out to our managers that no one has to do this. Thanks!