]> gitweb.factorcode.org Git - factor.git/blobdiff - basis/calendar/format/format.factor
calendar.elapsed: moving words to calendar.format.
[factor.git] / basis / calendar / format / format.factor
index 6c602008c4c20ada349b2e5d3ec093f9760a474f..617fff66f86770cf0cad5259f7aacad145c05abe 100644 (file)
@@ -1,8 +1,8 @@
 ! Copyright (C) 2008, 2010 Slava Pestov, Doug Coleman.
 ! See http://factorcode.org/license.txt for BSD license.
-USING: accessors arrays calendar calendar.english combinators io
-io.streams.string kernel math math.parser math.parser.private
-present quotations sequences words ;
+USING: accessors arrays calendar calendar.english combinators
+formatting io io.streams.string kernel make math math.parser
+math.parser.private present quotations sequences words ;
 IN: calendar.format
 
 MACRO: formatted ( spec -- quot )
@@ -207,3 +207,59 @@ M: timestamp present timestamp>string ;
             ] unless-zero
         ] [ duration>hms write ] tri
     ] with-string-writer ;
+
+GENERIC: elapsed-time ( seconds -- string )
+
+M: integer elapsed-time
+    dup 0 < [ "negative seconds" throw ] when [
+        {
+            { 60 "s" }
+            { 60 "m" }
+            { 24 "h" }
+            {  7 "d" }
+            { 52 "w" }
+            {  f "y" }
+        } [
+            [ first [ /mod ] [ dup ] if* ] [ second ] bi swap
+            dup 0 > [ number>string prepend , ] [ 2drop ] if
+        ] each drop
+    ] { } make [ "0s" ] [ reverse " " join ] if-empty ;
+
+M: real elapsed-time
+    >integer elapsed-time ;
+
+M: duration elapsed-time
+    duration>seconds elapsed-time ;
+
+M: timestamp elapsed-time
+    now swap time- elapsed-time ;
+
+! XXX: Anything up to 2 hours is "about an hour"
+: relative-time-offset ( seconds -- string )
+    abs {
+        { [ dup 1 < ] [ drop "just now" ] }
+        { [ dup 60 < ] [ drop "less than a minute" ] }
+        { [ dup 120 < ] [ drop "about a minute" ] }
+        { [ dup 2700 < ] [ 60 /i "%d minutes" sprintf ] }
+        { [ dup 7200 < ] [ drop "about an hour" ] }
+        { [ dup 86400 < ] [ 3600 /i "%d hours" sprintf ] }
+        { [ dup 172800 < ] [ drop "1 day" ] }
+        [ 86400 /i "%d days" sprintf ]
+    } cond ;
+
+GENERIC: relative-time ( seconds -- string )
+
+M: real relative-time
+    [ relative-time-offset ] [
+        dup abs 1 < [
+            drop
+        ] [
+            0 < "hence" "ago" ? " " glue
+        ] if
+    ] bi ;
+
+M: duration relative-time
+    duration>seconds relative-time ;
+
+M: timestamp relative-time
+    now swap time- relative-time ;