#!/usr/bin/env awk
#
# Converts timestamp 't' to string (localtime)
#
# The timestamp 't' can be provided as a Unix timestamp (SEC.USEC) or
# as a date formatted as follows: (YYYY-MM-DDTHH:MM:SS.USEC([+/-]OFFSET|Z)
# The microsecs are optional and the offset must be comprised of 2 or 4 digits
# or 'Z' for UTC. Note that the separating characters (-, T and :) can be
# any characters which are not numbers.
#
# Parameters:
#   - t: the time/date to convert
#
# Dependencies:
#   - None
#
# See Also:
#   - timestamp
#   - utc
#
# Examples:
#   - tawk '{
#         $timeFirst = localtime($timeFirst)
#         $timeLast  = localtime($timeLast)
#         print
#     }' file.txt
#   - tawk '{ print localtime($timeFirst) }' file.txt

function localtime(t,        _cmd, _d, _ms, _t) {
    if (match(t, /^([0-9]{4}[^0-9][0-9]{2}[^0-9][0-9]{2})[^0-9]([0-9]{2}[^0-9][0-9]{2}[^0-9][0-9]{2})(\.[0-9]+)?([+-][0-9]{2}([^0-9]?[0-9]{2})?|Z)$/, _d)) {
        if (__UNAME__ == "Darwin") {
            if (!_d[5]) _d[4] = _d[4] "00"
            _cmd = "date -j -u -f '%F %T%z' \"" _d[1] " " _d[2] "" _d[4] "\" \"+%s\""
        } else {
            _cmd = "date -u \"+%s\" -d \"" _d[1] " " _d[2] "" _d[4] "\""
        }
        _ms = _d[3]
        _cmd | getline _t
        close(_cmd)
    } else if (t !~ /^[0-9]+(\.[0-9]+)?$/) {
        return t
    } else {
        _t = t
        # microseconds
        if (t ~ /\.[0-9]+$/) {
            _ms = gensub(/^[0-9]+\./, ".", 1, t)
        }
    }

    if (!_ms) _ms = "" # ".000000"

    return strftime("%F %T", _t) "" _ms "" strftime("%z", _t)
}
