Version 2 of now

Updated 2017-08-23 20:43:20 by dbohdan

dbohdan 2017-08-23: now is a little date and time calculator utility for the command line. It leverages Tcl's clock add for date arithmetic.

Download with wiki-reaper: wiki-reaper -x 48963 0 | tee now.tcl

Code

#! /usr/bin/env tclsh
# now v0.2.0 copyright (c) 2017 dbohdan. License: MIT.
package require Tcl 8.5

proc usage {} {
    puts stderr [format {usage: %s [-format fmt] [-gmt 0/1] [-locale loc]\
                         [-timezone tz] [count unit ...]} \
                        [file tail [info script]]]
}

if {$argv in {-h --help}} {
    usage
    exit 0
}

set formatOpts {}
while {[lindex $argv 0] in {-format -gmt -locale -timezone}} {
    set argv [lassign $argv k v]
    lappend formatOpts $k $v
} 

if {[catch {
    puts [clock format [clock add [clock seconds] {*}$argv] {*}$formatOpts]
} res opts]} {
    set ec [dict get $opts -errorcode]
    switch -glob -- $ec {
        {CLOCK wrongNumArgs} {
            puts stderr "error: can't parse arguments \"$argv\""
            usage
        }
        {CLOCK badSwitch *} -
        {CLOCK badOption *} {
            puts stderr "error: unknown option \"[lindex $ec 2]\""
            usage
        }
        default { puts stderr "error: $res" }
    }
    exit 1
}

Use examples

$ now
Wed Aug 23 19:46:15 DST 2017
$ now -3491 days
Fri Feb 01 19:46:37 STD 2008
$ now -timezone :UTC -9 years -6 months -22 days +5 hours 5 minutes
Fri Feb 01 22:54:59 UTC 2008