#!/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 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:
#   - localtime
#   - utc
#
# Examples:
#   - tawk '{
#         $timeFirst = timestamp($timeFirst)
#         $timeLast  = timestamp($timeLast)
#         print
#     }' file.txt
#   - tawk '{ print timestamp($timeFirst) }' file.txt

function timestamp(t,        _cmd, _d, _year, _month, _day, _hours, _mins, _secs, _ms, _tz, _t, _date, _time, _datetime) {
    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)) {
        _year = _d[1]
        _month = _d[3] ? _d[3] : "01"
        _day = _d[5] ? _d[5] : "01"
        _hours = _d[7] ? _d[7] : "00"
        _mins = _d[9] ? _d[9] : "00"
        _secs = _d[11] ? _d[11] : "00"
        _ms = _d[12] ? _d[12] : "" # ".000000"
        _tz = _d[13]
        if (!_tz || _tz == "Z") _tz = "+0000"
        _date = _year "-" _month "-" _day
        _time = _hours ":" _mins ":" _secs
        _datetime = _date " " _time
        if (__UNAME__ == "Darwin") {
            if (length(_tz) == 3) _tz = _tz "00"
            _cmd = "date -j -u -f '%F %T%z' \"" _datetime "" _tz "\" \"+%s\""
        } else {
            _cmd = "date -u \"+%s\" -d \"" _datetime "" _tz "\""
        }
        _cmd | getline _t
        close(_cmd)
        return _t "" _ms
    }

    return t
}
