1

I have a method that returns the first day of the first week of a month, for making a little calendar:

def month_first_week_day(month, year)
  start = DateTime.civil(year, month, 1)

  start_date = DateTime.commercial(year, cweek, 1)
end

But I have this issue:

Date.civil(2011, 1, 1).cweek # => 52

I want it to return 1, not 52. I found this same problem in java here: Why does the en_GB locale think the 1st of January is the 52nd week of the year?.

Any suggestion?

Community
  • 1
  • 1
grilix
  • 5,211
  • 5
  • 33
  • 34
  • 2
    The 1st of January doesn't always class as being in the first week of the year. The initial week is defined by when the 1st falls, but when the first week of that year starts. By definition the 1st will fall in to the previous year 6 times out of 7. Because then the back end week in December would fall under week 1 to be defined as you expect. – Lloyd Powell Dec 12 '11 at 14:39
  • What criteria are you using to say that January 1st is always week 1? If `Friday Jan 1st` is week 1, what week is `Monday Jan 4th`? Is it still week 1 despite having a weekend in between? – Gareth Dec 12 '11 at 14:44
  • @Gareth it's a calendar-like view, the first week I should see, is the one that have Jan 1st, no matter what day it is. – grilix Dec 12 '11 at 15:44

2 Answers2

2

You could use Date.new(year, month).beginning_of_month instead of writing a function that does the same thing. See more here As an example

 Date.new(2011, 1).beginning_of_month
 => Sat, 01 Jan 2011

Edit: List of all the functions to do calculations on Date

cristian
  • 8,676
  • 3
  • 38
  • 44
  • begining_of_month is not what I need, but beginning_of_week is. Thanks for showing me the light! – grilix Dec 12 '11 at 15:48
2

I believe this is because a commercial week is always a period of time running from Sunday through Saturday, and therefore January 1, 2011 was part of the last commercial week of 2010.

January 1, 2011 fell on a Saturday.

January 2, 2011 was the first Sunday of 2011, and therefore commercial week #1 in 2011.

When you convert between commercial (business) time, and civil (calendar) time, you're occasionally going to run into these strange overlaps. They are essentially two separate calendars, which is why there are both civil and commercial conversions. The commercial time is especially useful to calculations involving accounting stuff, such as the end of a fiscal year (as opposed to the end of a calendar year), etc.

jefflunt
  • 33,527
  • 7
  • 88
  • 126