Essays/Timestamp Extension

From J Wiki
Jump to: navigation, search

Currently, 6!:0 '' returns the current time in order YMDHMS. This essay describes an extension to 6!:0 and the steps in its implementation.


Description

6!:0 y Current. The current time in the order year, month, day, hour, minute, second. The argument may be an empty vector, producing a 6-element numeric list; or a string of the letters Y M D h m s and other characters, producing a formatted string. For example:

   6!:0 ''
2007 10 30 13 10 45.312

   6!:0 'YYYY-MM-DD hh:mm:ss.sss'
2007-10-30 13:10:46.875

   6!:0 'hh:mm:ss MM/DD/YY'
13:10:48 10/30/07

Model

timestamp=: 3 : 0
 assert. (''-:y) +. (1>:#$y) *. (3!:0 y) e. 2 131072
 t=. 6!:0 ''
 if. ''-: y do. t return. end.
 q=. }.&.> ":&.> 100+t
 z=. y
 z=. z j}~ (4-#j)}.":{.t                [ j=. 'Y' I.@:= z
 z=. z j}~ (#j){.>1{q                   [ j=. 'M' I.@:= z
 z=. z j}~ (#j){.>2{q                   [ j=. 'D' I.@:= z
 z=. z j}~ (#j){.>3{q                   [ j=. 'h' I.@:= z
 z=. z j}~ (#j){.>4{q                   [ j=. 'm' I.@:= z
 z=. z j}~ (#j){.1 2 4 5 6{7j3":100+{:t [ j=. 's' I.@:= z
)

Test Script

A test script is script which contains purportedly true J sentences. Test scripts can be run with either 0!:2 or the 0!:3 . The following utility is assumed to be defined:

etx=: 1 : 'x :: (<:@(13!:11)@i.@0: >@{ 9!:8@i.@0:)'

Test script for the extended 6!:0 .

NB. 6!:0 ----------------------------------------------------------------

ts=: 6!:0

t=: ts ''
(,6) = $t
(-: <.) 5{.t
*./ 0 <: t
1990 <: 0{t
*./ (1&<: *. <:&12 31) 1 2{t
24 60 60 *./ . > 3 4 5{t

t=: ts x=: 'YYYY-MM-DD hh:mm:ss.sss'
t -:&$ x
t -:&(3!:0) x
t -:&((-.x e. 'YMDhms')&#) x

'domain error' -: ts etx 3 4 5
'domain error' -: ts etx <'YYYY-MM-DD hh:mm:ss.sss'

'rank error'   -: ts etx ,: 'YYYY-MM-DD hh:mm:ss.sss'

1 [ 6!:3 (55&< * 60&-) 5{ts ''  NB. delay till the new minute if close to it
(ts -: ts@u:) 'YYYY-MM-DD'
(ts -: ts@u:) 'MM/DD/YY hh:mm'
(":{.ts '') -: ts    'YYYY'
(":{.ts '') -: ts u: 'YYYY'
(_2{.":{.ts '') -: ts 'YY'


4!:55 ;:'t ts x'



Contributed by Roger Hui. Motivated by a message by Devon McCormick to the J Forum on 2007-10-30.