]> gitweb.factorcode.org Git - factor.git/commitdiff
calendar[-docs]: add week-number
authorAlexander Iljin <ajsoft@yandex.ru>
Wed, 17 Apr 2019 23:14:49 +0000 (01:14 +0200)
committerJohn Benediktsson <mrjbq7@gmail.com>
Thu, 18 Apr 2019 21:34:54 +0000 (14:34 -0700)
basis/calendar/calendar-docs.factor
basis/calendar/calendar-tests.factor
basis/calendar/calendar.factor

index 77705b2162dbd6fedda8c8f9beb26963fb35f612..3ca4e371b65c4927410781e1c408796deeb61f1a 100644 (file)
@@ -401,6 +401,22 @@ HELP: day-of-year
     }
 } ;
 
+HELP: week-number
+{ $values { "timestamp" timestamp } { "[1,53]" integer } }
+{ $description "Calculates the ISO 8601 week number from 1 to 53 (leap years). See " { $snippet "https://en.wikipedia.org/wiki/ISO_week_date" } }
+{ $examples
+    "Last day of 2018 is already in the first week of 2019."
+    { $example "USING: calendar prettyprint ;"
+               "2018 12 31 <date> week-number ."
+               "1"
+    }
+    "2020 is a leap year with 53 weeks, and January 1st, 2021 is still in week 53 of 2020."
+    { $example "USING: calendar prettyprint ;"
+               "2021 1 1 <date> week-number ."
+               "53"
+    }
+} ;
+
 HELP: sunday
 { $values { "timestamp" timestamp } { "new-timestamp" timestamp } }
 { $description "Returns the Sunday from the current week, which starts on a Sunday." } ;
@@ -573,6 +589,7 @@ ARTICLE: "calendar-facts" "Calendar facts"
     days-in-month
     day-of-year
     day-of-week
+    week-number
 }
 "Calculating a Julian day number:"
 { $subsections julian-day-number }
index 53780866bd5f2275339b3695889939f7f07516d9..fef64a0f289d5784b621cad532f29374ceadf127 100644 (file)
@@ -194,3 +194,9 @@ IN: calendar
 
 ! pm
 [ now 30 pm ] [ not-in-interval? ] must-fail-with
+
+{ 1 } [ 2018 12 31 <date> week-number ] unit-test
+
+{ 16 } [ 2019 4 17 <date> week-number ] unit-test
+
+{ 53 } [ 2021 1 1 <date> week-number ] unit-test
index 7875712de63072e5577570ff2c073c2fd3afdcd8..c42bba51f5ff1d60f1ff01ed1f9e4588bcbf26ee 100644 (file)
@@ -538,6 +538,16 @@ M: integer end-of-year 12 31 <date> ;
 : unix-time>timestamp ( seconds -- timestamp )
     [ unix-1970 ] dip +second ; inline
 
+: (week-number) ( timestamp -- [0,53] )
+    [ day-of-year ] [ day-of-week [ 7 ] when-zero ] bi - 10 + 7 /i ;
+
+: week-number ( timestamp -- [1,53] )
+    dup (week-number) {
+        {  0 [ year>> 1 - end-of-year (week-number) ] }
+        { 53 [ year>> 1 + <year> (week-number) 1 = 1 53 ? ] }
+        [ nip ]
+    } case ;
+
 {
     { [ os unix? ] [ "calendar.unix" ] }
     { [ os windows? ] [ "calendar.windows" ] }