Read more

Deal with different ways of counting weeks and weekdays in Ruby

Henning Koch
March 16, 2011Software engineer at makandra GmbH

Depending on where you live, different rules are used to determine the number of the week and a weekday. You have no chance Show archive.org snapshot whatsoever Show archive.org snapshot to get this right globally unless you make it your life's purpose. However, when you work for clients from Europe or the US, there are two dominantish standards you should know about. Each of these has subtle differences.

ISO 8601

  • This is adhered to by most European countries.
  • Weeks start on Monday and end on Sunday.
  • To get the number of the weekday in Ruby as defined by ISO 8601, use Date#cwday Show archive.org snapshot , which returns values in 1..7 (mind the range difference to Date#wday Show archive.org snapshot ).
  • The first week of the year is the week with January 4th in it. All days in this week belong to the year. This means that January 1st, 2nd and 3rd may or may not be part of the previous year's last calendar week. Also December 29th, 30th and 31st may or may not be part of the upcoming year's first calendar week.
  • To get the calendar week in Ruby as defined by ISO 8601, use Date#cweek Show archive.org snapshot , which returns values in 1..53

USA and Canada

  • Not defined in a standard.
  • Weeks start on Sunday and end on Saturday.
  • To get the number of the weekday in Ruby as used in the USA, use Date#wday Show archive.org snapshot , which returns values in 0..6 (mind the range difference to Date#cwday Show archive.org snapshot )
  • January 1st is part of the first week of the year. I am not sure which year December days in the same week belong to, I believe the week actually gets split into two calendar weeks in two different years (please change this note if you know).
  • AFAIK there is no Ruby method to get the calendar week of a Date as used in the USA.
Illustration UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
Read more Show archive.org snapshot
Posted by Henning Koch to makandra dev (2011-03-16 17:44)