Skip to content

Conversation

@cspiel
Copy link
Collaborator

@cspiel cspiel commented Feb 5, 2020

Previous Class Tm

Class Tm provides all components of the "usual" broken-down date-time,
but it is tedious to produce a nicely formatted date-time tag for example for
a subdirectory. The author of this pull request ended up writing a monstrosity like
this for a RFC-3339 formatted date-time:

date_rfc_3339(~use_localtime, ?timespec = $'seconds') =
        pad02(a_number) =
                if $(le $(a_number), 9)
                    return $'0'$(a_number)
                else
                    return $(a_number)

        localtime = $(localtime $(gettimeofday))
        gmtime = $(gmtime $(gettimeofday))
        if $(use_localtime)
            now = $(localtime)
            offset_hour = $(pad02 $(sub $(localtime.tm_hour), $(gmtime.tm_hour)))
            offset_minute = $(pad02 $(sub $(localtime.tm_min), $(gmtime.tm_min)))
            export
        else
            now = $(gmtime)
            offset_hour = $'00'
            offset_minute = $'00'
            export

        year = $(add 1900, $(now.tm_year))
        month = $(pad02 $(add 1, $(now.tm_mon)))
        day_of_month = $(pad02 $(add 1, $(now.tm_mday)))

        hour = $(pad02 $(now.tm_hour))
        minute = $(pad02 $(now.tm_min))
        second = $(pad02 $(now.tm_sec))

        switch $(timespec)
        case date
            return $(concat $'-', $(year) $(month) $(day_of_month))
        case seconds
            return $(concat $'-', $(year) $(month) $(day_of_month)) $(concat $':', $(hour) $(minute) $(second))+$(offset_hour):$(offset_minute)
        default
            raise $'unknown timespec value'

New Method tm_format

This p/r adds a method called tm_format to the Tm class that
works like strftime(3) as specified by POSIX plus some GLibc extensions
minus all locale functionality. The above RFC-3339 example now boils
down to more or less

now = $(gettimeofday)
datetime = $(gmtime $(now))
println($(datetime.tm_format $'%Y-%m-%dT%H:%M:%S%z'))
println($(datetime.tm_format $'%FT%T%z')) # use predefined conversions

Implementation

I have attached the method as a Omake_value_type.ValPrim in Omake_builtin_sys.tm_object.
My attempts to use Omake_value_type.ValFun failed because the statements associated
with ValFun get executed on object construction time; they are not delayed until the method
gets called. Maybe someone with a more profound insight into the IR can suggest a better
Omake_value_type for the method.

The new method works like strftime(3).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants