Getting week of the month from a DateTime variable?

Hello,


How do I get the week number of the month a DateTime value falls under? For example, March 3, 2007 would be in week 1 and March 4, 2007 would be in week 2


 

thx 

0
Totenkopf
3/27/2007 7:51:00 PM
asp.net.getting-started 91979 articles. 4 followers. Follow

3 Replies
456 Views

Similar Articles

[PageSpeed] 3

theres no native week of month function. The closest you can get is GetWeekInYear , which you can pass the 1st day of the month, along with the day of week that the week starts on. You can then loop, adding 7 days to the date to calculate the other weeks in the month.

Cathal

0
cathal
3/27/2007 8:42:24 PM

http://groups.google.com/group/microsoft.public.access/msg/996e69eb76a63f76

 

 

Wayne Morgan wrote:
> This one is a little simpler.

> Public Function WeekOfMonth(dteInputDate As Date) As Integer
> Dim intDate As Integer
> intDate = Day(dteInputDate)
> WeekOfMonth = (intDate \ 7) + 1 + (intDate Mod 7 = 0)
> End Function

Here's a more general version:

Public Function WeekOfMonth(dteInputDate As Date, intStartWeekday As
Integer) As Integer
Dim intWeekdayOf1st As Integer
Dim intDaysInWeek1 As Integer
Dim intDaysPastWeek1 As Integer

intWeekdayOf1st = WeekDay(DateSerial(Year(dteInputDate),
Month(dteInputDate), 1))
intDaysInWeek1 = (6 + intStartWeekday - intWeekdayOf1st) Mod 7 + 1
If Day(dteInputDate) <= intDaysInWeek1 Then
   WeekOfMonth = 1
Else
   intDaysPastWeek1 = Day(dteInputDate) - intDaysInWeek1
   WeekOfMonth = 1 + (intDaysPastWeek1 \ 7) + Abs(intDaysPastWeek1 Mod 7
<> 0)
End If
End Function

Note: This function can be shortened slightly by using the Ceiling(X) =
- Int(-X) function posted by Van T. Dinh:
WeekOfMonth = 1 - Int(-intDaysPastWeek1 / 7)
When used in a query, use the weekday numbers (Sunday = 1, ..., Saturday
= 7) directly instead of vbSunday, ..., vbSaturday.  It counts the days
during the month before the first starting weekday, if any, as week 1.

Also, see the technique used in:

http://groups.google.com/group/microsoft.public.access/msg/c777af0e1f...

Note: The Ceiling function can similarly simplify the expression used there.

James A. Fortune 
  


Please remember to "mark as answered" posts that have helped you.

-----
http://lsudotnet.blogspot.com
0
LSU
3/27/2007 8:46:00 PM
 
    // ---- GetWeekOfMonth ---------------------------
    //
    // Assuming Sunday starts a new week, get the ordinal
    // week a date is in...of the date's month
    // using Microsoft.VisualBasic;

    int GetWeekOfMonth(DateTime Date)
    {
        long Week;

        // get first day of month
        DateTime BaseDate = new DateTime(Date.Year, Date.Month, 1);

        // get difference, in weeks, between the date and first day of month
        Week = DateAndTime.DateDiff(DateInterval.WeekOfYear, 
                                    BaseDate, 
                                    Date, 
                                    Microsoft.VisualBasic.FirstDayOfWeek.Sunday, 
                                    FirstWeekOfYear.Jan1);
        
        // want it one, not zero based
        return (int)Week + 1;
    }

    // test it
    protected void Button1_Click(object sender, EventArgs e)
    {
        DateTime Date = new DateTime(2007, 3, 1);

        while (Date.Month == 3)
        {
            int Week = GetWeekOfMonth(Date);

            Response.Write(String.Format("{0:d} : {1} <BR>", Date, Week));
            Date = Date.AddDays(1);
        }
    }
 
Steve Wellens

My blog
0
SGWellens
3/27/2007 9:45:29 PM
Reply:

Similar Artilces:

POST GET GET GET GET... WTH?
Hi, I'm at a loss to explain this... I have an ASPX page that I can't always navigate to. When I developed the app (it's Starter Kit Portal-based), I did it on my LAN and have had no trouble accessing the page. However, upon deployment, I see the following behavior: 1. POST request goes out looking for MyForm.aspx 2. GET request for MyForm.aspx 3. GET request for MyForm.aspx 4. ... X. GET request Sometimes, the page finally loads. Other times, it just ends up blank. Many times, it doesn't load at ALL the first POST - I just get a "The pa...

Getting variables from a post or get?
Sorry for the newbie post, but i am from a PHP world. Im now learning ASP.NET.Im having a bit of problem figuring out how to get/post a variable on an input field. All i want to do is, get the value from an input form and display it again on the page. Here's my code.. <form id="form1" runat="server" acceptcharset="utf-8"> Your name: <input id="name" name="name" type="text" /> <asp:Button ID="Button1" runat="server" Text="Button" PostBackUrl="Default.aspx" /> </form> All i want is to get the value of name and display it on the page it self. How can i do that...

Get week numbers 1 TO 52 starting in another month rather than january
Hi folks,Anyone here know of a function or seen anything on the net where I can count the weeks from one to 53 in a year? - except the year starts on April 1st 2008 and ends on March 31st 2009 - im doing this to sync my tax yearSpent the last hour trying to think of how to do one - more difficult than I imagined! Not sure exactly what you are trying to do... If you are trying to use a specific Date to tell you what week you are in you could turn the date into a week number by multiplying the month number -1 * 4 plus however many weeks are in the current month number and then subtract the ...

trying to get started and i am getting this error
when i go to http://www.porkchopsplayground.com, i get: DotNetNuke Upgrade Error The Assembly Version ( [ASSEMBLYVERSION] ) does not match the Database Version ( [DATABASEVERSION] ) ERROR: Could not connect to database. Could not find file 'd:\hosting\nmoran26\Providers\DataProviders\AccessDataProvider\DotNetNuke.mdb'. Any suggestions will be appreciated. Thanks, Nicole Do you have a username and password set on your database? Make sure you follow the steps mentionned in the Readme.txt located in the documentation folder. In any case make sure your credentials for yo...

Getting the start of a week
Hi i have a stored procedure which is returning the days of a month that are stored in my dataabse, what i am trying to do now is to get the start and ending of each week, is this possible, this is what i have done so far; select CAST (a.AvailabilityDay as varchar(2)) + ' ' + datename(month,'01/'+convert(varchar(2),am.availabilityMonth)+'/'+convert(varchar(4),am.availabilityYear)) + ' '+ CAST(am.AvailabilityYear AS VARCHAR(4)) AS AvailabilityDay, AvailabilityPrice, bBooked, AVAILABILITY_ID, AvailabilityMonthID, am.AVAILABILITYMONTH_ID From Availability a, ...

how to get start with .NET
the net help people installed  to my desktop 1-microsoft visual studio .NET enterprise developer 2003 2-microsoft .NET framework 1.1 what else do i need ...???  and how can i try with some simple code in VS.Net and run it to see wat happen...????? please help If you want to develope web applications, then you'll also need IIS on your PC.  That'll require XP-Professional or Windows 2000/2003, but XP-Home edition won't allow IIS installation. As for how to get started, you can search the web for some tutorials or buy a good book on VS.  The topic is way too vast to...

Getting Start With .net
hi i'm intersted to learn asp.net (vb or delphi) . i programming with delphi6 but i'd like to tp know something about programming in internet specially with .net . i hear about microsoft.net with delphi 7 that i can programming with delphi in .net .... is it right ? what 's our opinian about it ? and better to learn Vb.Net or continu with delphi(or delphi.net) thanks. Ali Darabian I think there is some support for Delphi in .Net. However, you will find much more support from the user community if you choose a more popular language such as VB.Net or C#. Since your al...

Getting error in Net::SFTP with get function
------=_Part_7028_3315294.1193837808284 Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: 7bit Content-Disposition: inline Hi All, I have the following code as part of my program; print "---=========> $file, $localFile\n"; $sftp -> get( $file, $localFile ) || warn("errrrr0rrrrr _---> $!".$sftp->status."\n");^M Even though it has downloaded the file properly, it is giving the following message: ---=========> /trading/tiscrdenhlist10310000.txt.old, /export/home/crdadm/rajeev/tiscrdenhlist103...

get rid of that ridiculous getting started bookmark
Name: DOCTOR Product: Firefox Summary: get rid of that ridiculous getting started bookmark Comments: Browser Details: Mozilla/5.0 (Macintosh; U; PPC Mac OS X 10_4_11; en) AppleWebKit/525.18 (KHTML, like Gecko) Version/3.1.2 Safari/525.22 From URL: http://hendrix.mozilla.org/ Note to readers: Hendrix gives no expectation of a response to this feedback but if you wish to provide one you must BCC (not CC) the sender for them to see it. ...

getting started in VS2005 C# which book should I get
Hello, I am getting started with VS2005, I have use VS2003 but not very much -(I did 4 small applications in it),  I am wondering which book you would recommend to learn the new features of VS2005, while learning more of C# programing in general There some links to good books in this thread i posted : http://forums.asp.net/thread/1489422.aspx Also these two make good reference material  Professional Visual Studio 2005 (Programmer to Programmer)   Microsoft Visual Studio 2005 Unleashed  So far I recommend Wrox's C# 2005  Read the beginning chap...

Where to start and how did you get started?
Hi, I have had a feeling for a long time to jump into the adds market for some time due to my low income (shooting for the stars) and I don't have anything better to do these days. But I find it really difficult not to give up due to lack of guides (what I can find atleast) and all the hard words which only makes me confused. But I won't give up. Never. Not sure if this is the right place to post this, but I deffinitly would be really greatfull for help getting started. How did you get started? +If there are any teacher that wanna show me the ropes private, I can give payment with ...

How to get week start date, End date for a given week nunber,year?
I want  a javascript function to to get the starting date and end date of a week when I have given the week number (1 to 5), Month number (1 to 12), valid year as parameter. How to do that?Manivannan  You can visited http://www.datejs.com/2007/11/I dont have example.Hope it's help you. try this example function GetWeekStartEndDate(){    var week = 5;    var month = 4;    var year = 2008;        var PositiveOneDay = new Date(new Date('1/2/2000') - new Date('1/1/2000'));   &...

How do I get started with AJAX.Net?
Hi All, I'm a seasoned asp.net developer but have not yet ventured into atlas et al.  I prefer books, but will take whatever I can get if it's good and will get me going. Any recommendations? Thx in advance. Jeff try here first http://ajax.asp.net/downloads/default.aspx?tabid=47 then learn from sample and docJames Wu (MIB426).NET is only way to goMCP, MCSE, MCDBA, MCSD, MCAD I find the materials online display features and implementations but are lacking architectural depth, and am seeking more comprehensive resources. By architectural depth, I mean that I cannot watch ...

when I get the DateTime of Today, How to get the day of last Monday?
hi there I use c# 1.0 I use DateTime.Now to Get the Date of Today assume today is 11/30 Friday, How to get the day of last Monday and last Sunday?   ( the Last Monday should be 11/19 and Sunday should be 11/25)  I need to use the Day I get from DateTime.Now to get the last Monday and Sunday..   thank you Well it depends on whether the date you're looking for is relative to 'today'.E.g. You say you want to know how to find the date for 'last monday'. Will you always be looking for last monday regardless of what day it is today? Will you always...

Web resources about - Getting week of the month from a DateTime variable? - asp.net.getting-started

Variable - Wikipedia, the free encyclopedia
Text is available under the Creative Commons Attribution-ShareAlike License ;additional terms may apply. By using this site, you agree to the ...

Westpac interest rate rise is one of many variable loan rate rises
WESTPAC is not alone in hitting its owner-occupier customers with a surprise interest rate rise, as dozens of other variable rate home loans ...

Airbnb upgrades variable pricing tool for hosts
Online home rental group Airbnb is rolling out an upgraded variable pricing tool that automatically raises or cuts room rates based on supply ...

Commonwealth Bank raises variable home loan rates
Home owners' mortgage costs are set to rise by hundreds of dollars a year, after the Commonwealth Bank became the latest bank to hike interest ...

CBA lifts variable home loan rates to offset costs associated with stricter capital requirements
The Commonwealth Bank to lift its home loan interest rates independently of the Reserve Bank to partially offset costs associated with stricter ...

Washington Square Signs Spielbergs, Choi Joins Variable and More
... films and an episode of the HBO comedy series "Girls," on which he plays the role of Ray Ploshansky. New York-based creative collective Variable ...

YouTube v10.32 Tweaks Some Interface Elements And Includes Hints About Virtual Reality Content And Variable ...
Forget Update Wednesday! Monday is the new big day. Not only were we treated to the latest M preview release and the official Marshmallow name, ...

"You have to ignore many variables to think women are paid less than men. California is happy to try." ...
Writes Sarah Ketterer in The Wall Street Journal in "The ‘Wage Gap’ Myth That Won’t Die" (which you can get to without subscribing if you Google ...

Staley: 'A lot of different variables...been a hard year'
... 41° Navigation Home Giants A's Sharks Warriors Kings 49ers Raiders Quakes Insiders More Tickets Shop Watch Staley: 'A lot of different variables...been ...

Expert Reveals the Latest Variable Capacity Technology
Learn about gForce Ultra CRAC equipment, the latest variable capacity technology to lower energy usage and increase reliability.

Resources last updated: 1/28/2016 7:53:41 PM