commit ddc9ef9f45cfaafe4e5294d82dd76ccd6c5b843d
parent 8be5b06171e57cfffce26d8020015ffab452b35b
Author: Jacob R. Edwards <jacob@jacobedwards.org>
Date: Sun, 10 Mar 2024 22:15:27 -0700
Localize date and times using JavaScript
I'd rather do this server-side since one goal for the project is
to work gracefully without scripts if the user agent doesn't
provide/enable them, but I actually don't know of a C library that
can localize time to a specified locale. I may end up just having
to write my own, but here's this for now.
Diffstat:
2 files changed, 25 insertions(+), 1 deletion(-)
diff --git a/pages/main.c b/pages/main.c
@@ -285,7 +285,9 @@ pagemain(struct pagedata *pd)
err(1, "gettimes");
if ((status = htmlwithin(pd, KELEM_H1, "Timekeeper")) != KCGI_OK ||
- (status = printtimes(pd, times, ntimes)) != KCGI_OK) {
+ (status = printtimes(pd, times, ntimes)) != KCGI_OK ||
+ (status = khtml_attr(&pd->html, KELEM_SCRIPT,
+ KATTR_SRC, "scripts/localize.js", KATTR__MAX)) != KCGI_OK) {
free(times);
return status;
}
diff --git a/scripts/localize.js b/scripts/localize.js
@@ -0,0 +1,22 @@
+function localize_time(time) {
+ let date = new Date(Date.parse(time.dateTime))
+ let options = {
+ "hour12": false,
+ "hour": "2-digit",
+ "minute": "2-digit"
+ }
+ time.textContent = date.toLocaleTimeString([], options)
+}
+
+function localize_date(time) {
+ let date = new Date(Date.parse(time.textContent))
+ let options = {
+ "year": "numeric",
+ "month": "2-digit",
+ "day": "2-digit"
+ }
+ time.textContent = date.toLocaleDateString([], options)
+}
+
+document.querySelectorAll("td:not(:nth-child(6))>time").forEach(localize_time)
+document.querySelectorAll("th[scope=\"row\"]>time").forEach(localize_date)