Created
March 4, 2014 14:13
-
-
Save draegtun/9347170 to your computer and use it in GitHub Desktop.
ISO week date conversions in Rebol
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Rebol [] | |
; see - http://codegolf.stackexchange.com/questions/22268/convert-calendar-dates-to-week-dates-and-vice-versa | |
; | |
; Grrr.. question now doesn't allow languages that use date/time operators :( | |
; So here the beginning is my (not golfed) version prior to the change! :) | |
; | |
; 28-Feb-2014 | |
to-iso-week: func [date [date!] /local week-day last-year? week-in-year?] [ | |
week-day: to-integer (date/yearday - date/weekday + 10 / 7) | |
last-year?: does [date/year - 1] | |
next-year?: does [date/year + 1] | |
weeks-in-year?: has [d] [ | |
d: make date! reduce [last-year? 1 1] | |
either all [d/weekday >= 5 d/weekday <= 7] [52][53] | |
] | |
format/pad [-4 "-W" -2 "-" -1] reduce switch/default week-day [ | |
0 [ | |
[last-year? weeks-in-year? date/weekday] | |
] | |
53 [ | |
d: from-iso-week format/pad [-4 "-W" -2 "-" -1] reduce [date/year week-day date/weekday] 0 | |
either/only d > date [date/year 53 date/weekday][next-year? 1 date/weekday] | |
] | |
][ | |
[date/year week-day date/weekday] | |
] 0 | |
] | |
from-iso-week: func [week-date /local year week weekday digit] [ | |
unless parse week-date [ | |
(digit: charset "0123456789") | |
copy year 1 4 digit | |
"-W" | |
copy week 2 digit | |
#"-" | |
copy weekday 1 digit | |
][return none] | |
use [ordinal correction] [ | |
correction: to-date join "4-Jan-" year | |
ordinal: (to-integer week) * 7 + (to-integer weekday) - (correction/weekday + 3) | |
(to-date join "1-Jan-" year) - 1 + ordinal | |
] | |
] | |
i: input | |
print either error? try [d: to-date i][ | |
; it's not a date so try ISO week date | |
d: from-iso-week i | |
format/pad [-4 "-" -2 "-" -2] reduce [d/year d/month d/day] 0 | |
][ | |
; it is a date! so convert to iso-week date | |
;format/pad [-4 "-W" -2 "-" -1] reduce [d/year to-iso-week d d/weekday] 0 | |
to-iso-week d | |
] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment