site-josuah

/usr/josuah
Log | Files | Refs

commit 2f73527f2f01a9c1a8d50f2220d85bab0a2cf826
parent 047449fba34f58be0d32fe1dd43d39a609aae887
Author: Josuah Demangeon <me@josuah.net>
Date:   Tue, 19 May 2020 20:50:48 +0200

add a mktime() awk function

Diffstat:
Mwiki/awk/index.md | 39+++++++++++++++++++++++++++++++++++++++
1 file changed, 39 insertions(+), 0 deletions(-)

diff --git a/wiki/awk/index.md b/wiki/awk/index.md @@ -309,3 +309,42 @@ command: Note that date(1) will only be called the first time localtime() is called, and the TZOFFSET global variable will be used for the next calls. + + +A mktime() function +------------------- +Complementary function to gmtime is mktime for converting a tm[] array back to +an integer representation. This is useful for parsing time values back to an +unix timestamp: + + function isleap(year) + { + return (year % 4 == 0) && (year % 100 != 0) || (year % 400 == 0) + } + + function mdays(mon, year) + { + return (mon == 2) ? (28 + isleap(year)) : (30 + (mon + (mon > 7)) % 2) + } + + function mktime(tm, + sec, mon, day) + { + sec = tm["sec"] + tm["min"] * 60 + tm["hour"] * 3600 + + day = tm["mday"] - 1 + + for (mon = tm["mon"] - 1; mon > 0; mon--) + day = day + mdays(mon, tm["year"]) + + # constants: x * 365 + x / 400 - x / 100 + x / 4 + day = day + int(tm["year"] / 400) * 146097 + day = day + int(tm["year"] % 400 / 100) * 36524 + day = day + int(tm["year"] % 100 / 4) * 1461 + day = day + int(tm["year"] % 4 / 1) * 365 + + return sec + (day - 719527) * 86400 + } + +All the following fields of tm[] must be defined: "year", "mon", "mday", +"hour", "min", "sec".