forked from cotes2020/jekyll-theme-chirpy
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlocale-datetime.js
More file actions
53 lines (45 loc) · 1.4 KB
/
locale-datetime.js
File metadata and controls
53 lines (45 loc) · 1.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/**
* Update month/day to locale datetime
*
* Requirement: <https://github.com/iamkun/dayjs>
*/
/* A tool for locale datetime */
class LocaleHelper {
static get attrTimestamp() {
return 'data-ts';
}
static get attrDateFormat() {
return 'data-df';
}
static get locale() {
return document.documentElement.getAttribute('lang').substring(0, 2);
}
static getTimestamp(elem) {
return Number(elem.getAttribute(this.attrTimestamp)); // unix timestamp
}
static getDateFormat(elem) {
return elem.getAttribute(this.attrDateFormat);
}
}
export function initLocaleDatetime() {
dayjs.locale(LocaleHelper.locale);
dayjs.extend(window.dayjs_plugin_localizedFormat);
document
.querySelectorAll(`[${LocaleHelper.attrTimestamp}]`)
.forEach((elem) => {
const date = dayjs.unix(LocaleHelper.getTimestamp(elem));
const text = date.format(LocaleHelper.getDateFormat(elem));
elem.textContent = text;
elem.removeAttribute(LocaleHelper.attrTimestamp);
elem.removeAttribute(LocaleHelper.attrDateFormat);
// setup tooltips
if (
elem.hasAttribute('data-bs-toggle') &&
elem.getAttribute('data-bs-toggle') === 'tooltip'
) {
// see: https://day.js.org/docs/en/display/format#list-of-localized-formats
const tooltipText = date.format('llll');
elem.setAttribute('data-bs-title', tooltipText);
}
});
}