1 ! Copyright (C) 2008 John Benediktsson
2 ! See http://factorcode.org/license.txt for BSD license
4 USING: accessors arrays calendar io kernel fry macros math
5 math.functions math.parser peg.ebnf sequences strings vectors ;
9 : >timestring ( timestamp -- string )
10 [ hour>> ] keep [ minute>> ] keep second>> 3array
11 [ number>string 2 CHAR: 0 pad-left ] map ":" join ; inline
13 : >datestring ( timestamp -- string )
14 [ month>> ] keep [ day>> ] keep year>> 3array
15 [ number>string 2 CHAR: 0 pad-left ] map "/" join ; inline
17 : (week-of-year) ( timestamp day -- n )
18 [ dup clone 1 >>month 1 >>day day-of-week dup ] dip > [ 7 swap - ] when
19 [ day-of-year ] dip 2dup < [ 0 2nip ] [ - 7 / 1+ >fixnum ] if ;
21 : week-of-year-sunday ( timestamp -- n ) 0 (week-of-year) ; inline
23 : week-of-year-monday ( timestamp -- n ) 1 (week-of-year) ; inline
28 EBNF: parse-format-string
30 fmt-% = "%" => [[ [ "%" ] ]]
31 fmt-a = "a" => [[ [ dup day-of-week day-abbreviation3 ] ]]
32 fmt-A = "A" => [[ [ dup day-of-week day-name ] ]]
33 fmt-b = "b" => [[ [ dup month>> month-abbreviation ] ]]
34 fmt-B = "B" => [[ [ dup month>> month-name ] ]]
35 fmt-c = "c" => [[ [ "Not yet implemented" throw ] ]]
36 fmt-d = "d" => [[ [ dup day>> number>string 2 CHAR: 0 pad-left ] ]]
37 fmt-H = "H" => [[ [ dup hour>> number>string 2 CHAR: 0 pad-left ] ]]
38 fmt-I = "I" => [[ [ dup hour>> 12 > [ 12 - ] when number>string 2 CHAR: 0 pad-left ] ]]
39 fmt-j = "j" => [[ [ dup day-of-year number>string ] ]]
40 fmt-m = "m" => [[ [ dup month>> number>string 2 CHAR: 0 pad-left ] ]]
41 fmt-M = "M" => [[ [ dup minute>> number>string 2 CHAR: 0 pad-left ] ]]
42 fmt-p = "p" => [[ [ dup hour>> 12 < [ "AM" ] [ "PM" ] ? ] ]]
43 fmt-S = "S" => [[ [ dup second>> round number>string 2 CHAR: 0 pad-left ] ]]
44 fmt-U = "U" => [[ [ dup week-of-year-sunday ] ]]
45 fmt-w = "w" => [[ [ dup day-of-week number>string ] ]]
46 fmt-W = "W" => [[ [ dup week-of-year-monday ] ]]
47 fmt-x = "x" => [[ [ dup >datestring ] ]]
48 fmt-X = "X" => [[ [ dup >timestring ] ]]
49 fmt-y = "y" => [[ [ dup year>> 100 mod number>string ] ]]
50 fmt-Y = "Y" => [[ [ dup year>> number>string ] ]]
51 fmt-Z = "Z" => [[ [ "Not yet implemented" throw ] ]]
52 unknown = (.)* => [[ "Unknown directive" throw ]]
54 formats_ = fmt-%|fmt-a|fmt-A|fmt-b|fmt-B|fmt-c|fmt-d|fmt-H|fmt-I|
55 fmt-j|fmt-m|fmt-M|fmt-p|fmt-S|fmt-U|fmt-w|fmt-W|fmt-x|
56 fmt-X|fmt-y|fmt-Y|fmt-Z|unknown
58 formats = "%" (formats_) => [[ second '[ _ dip ] ]]
60 plain-text = (!("%").)+ => [[ >string '[ _ swap ] ]]
62 text = (formats|plain-text)* => [[ reverse [ [ [ push ] keep ] append ] map ]]
68 MACRO: strftime ( format-string -- )
69 parse-format-string [ length ] keep [ ] join
70 '[ _ <vector> @ reverse concat nip ] ;