Nicholas Namacha
Nicholas Namacha

Reputation: 19

Determining which Sunday in Ruby

Using Ruby how can you determine if the coming Sunday is the first, second or third Sunday of the month?

Upvotes: 2

Views: 127

Answers (1)

user180247
user180247

Reputation:

@ElYusubov - is close, but not quite right.

As a starting point, the division must be by seven (number of days in a week). But time.day gives a day-of-the-month from 1 to 31, so first you need to subtract one before the division and add one after. The first eight days of any month give...

Day number    (Day# - 1) / 7    Week#
----------    --------------    -----
         1      0.0             1
         2      0.14            1
         3      0.29            1
         4      0.43            1
         5      0.57            1
         6      0.71            1
         7      0.86            1
         8      1               2

Whichever day-of-the-week time.day gives, that week# indicates whether it's the first, second etc of that day-of-the-week. But you want the coming Sunday.

wday gives a weekday - 0 to 6, with 0 meaning Sunday. So how many days are there to the coming Sunday? Well, that depends on your definition of "Coming", but if you exclude today==Sunday, you basically subtract todays weekday from 7.

Weekday today     Days until next Sunday
-------------     ----------------------
 0 (Sun)           7
 1 (Mon)           6
 2 (Tue)           5
 3 (Wed)           4
 4 (Thu)           3
 5 (Fri)           2
 6 (Sat)           1

If you allow the "coming" Sunday to be today, then you do the same thing but replace seven with zero. You can either do a conditional check, or use the modulo/remainder operator.

Anyway, once you know how many days ahead the coming Sunday is, you can calculate the date value for that (add those days to todays date) and then determine the week number in the month for that date instead of today using the first method (subtract 1, divide by seven, add 1).

Relevant vocabulary...

Date.wday        0 to 6 (0 = sunday)
Date.day         1 to 31

I won't try to provide the code because I don't know Ruby.

Upvotes: 3

Related Questions