#!/usr/bin/env awk
#
# Converts timestamp 't' to Unix timestamp
#
# 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 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:
#   - localtime
#   - utc
#
# Examples:
#   - tawk '{
#         $timeFirst = timestamp($timeFirst)
#         $timeLast  = timestamp($timeLast)
#         print
#     }' file.txt
#   - tawk '{ print timestamp($timeFirst) }' file.txt

function timestamp(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)) {
        _cmd = "date -u \"+%s\" -d \"" _d[1] " " _d[2] "" _d[4] "\""
        _ms = _d[3]
        _cmd | getline _t
        close(_cmd)
        if (!_ms) _ms = "" # ".000000"
        return _t "" _ms
    }

    return t
}
