cosmopolitan/examples/date.c

94 lines
2.9 KiB
C
Raw Permalink Normal View History

2020-06-15 14:18:57 +00:00
#if 0
/*─────────────────────────────────────────────────────────────────╗
To the extent possible under law, Justine Tunney has waived
all copyright and related or neighboring rights to this file,
as it is written in the following disclaimers:
http://unlicense.org/ │
http://creativecommons.org/publicdomain/zero/1.0/ │
*/
#endif
2023-06-10 22:50:01 +00:00
#include "libc/calls/calls.h"
#include "libc/calls/struct/timespec.h"
#include "libc/intrin/kprintf.h"
#include "libc/macros.internal.h"
#include "libc/nt/enum/timezoneid.h"
#include "libc/nt/struct/timezoneinformation.h"
#include "libc/nt/time.h"
#include "libc/runtime/runtime.h"
#include "libc/stdio/stdio.h"
2023-06-10 22:50:01 +00:00
#include "libc/str/str.h"
#include "libc/thread/threads.h"
#include "libc/time.h"
2020-06-15 14:18:57 +00:00
/**
2023-06-10 22:50:01 +00:00
* @fileoverview High performance ISO-8601 timestamp formatter.
*
* The strftime() function is very slow. This goes much faster.
* Consider using something like this instead for your loggers.
2020-06-15 14:18:57 +00:00
*/
2023-06-10 22:50:01 +00:00
char *GetTimestamp(void) {
int x;
struct timespec ts;
thread_local static long last;
thread_local static char s[32];
thread_local static struct tm tm;
2023-06-10 22:50:01 +00:00
clock_gettime(0, &ts);
if (ts.tv_sec != last) {
localtime_r(&ts.tv_sec, &tm);
x = tm.tm_year + 1900;
s[0] = '0' + x / 1000;
s[1] = '0' + x / 100 % 10;
s[2] = '0' + x / 10 % 10;
s[3] = '0' + x % 10;
s[4] = '-';
x = tm.tm_mon + 1;
s[5] = '0' + x / 10;
s[6] = '0' + x % 10;
s[7] = '-';
x = tm.tm_mday;
s[8] = '0' + x / 10;
s[9] = '0' + x % 10;
s[10] = 'T';
x = tm.tm_hour;
s[11] = '0' + x / 10;
s[12] = '0' + x % 10;
s[13] = ':';
x = tm.tm_min;
s[14] = '0' + x / 10;
s[15] = '0' + x % 10;
s[16] = ':';
x = tm.tm_sec;
s[17] = '0' + x / 10;
s[18] = '0' + x % 10;
s[19] = '.';
s[26] = 0;
last = ts.tv_sec;
}
x = ts.tv_nsec;
s[20] = '0' + x / 100000000;
s[21] = '0' + x / 10000000 % 10;
s[22] = '0' + x / 1000000 % 10;
s[23] = '0' + x / 100000 % 10;
s[24] = '0' + x / 10000 % 10;
s[25] = '0' + x / 1000 % 10;
s[26] = tm.tm_gmtoff < 0 ? '-' : '+';
x = ABS(tm.tm_gmtoff) / 60 / 60;
s[27] = '0' + x / 10 % 10;
s[28] = '0' + x % 10;
x = ABS(tm.tm_gmtoff) / 60 % 60;
s[29] = '0' + x / 10 % 10;
s[30] = '0' + x % 10;
2023-06-10 22:50:01 +00:00
return s;
}
2020-06-15 14:18:57 +00:00
int main(int argc, char *argv[]) {
2023-06-10 22:50:01 +00:00
char buf[128], *p = buf;
// setenv("TZ", "UTC", true);
// setenv("TZ", "US/Eastern", true);
// setenv("TZ", "Asia/Kolkata", true);
2023-06-10 22:50:01 +00:00
p = stpcpy(p, GetTimestamp());
p = stpcpy(p, "\n");
write(1, buf, p - buf);
2020-06-15 14:18:57 +00:00
}