Skip to content

Commit a7de567

Browse files
committed
add timeformat converter
1 parent ed157c1 commit a7de567

File tree

2 files changed

+114
-64
lines changed

2 files changed

+114
-64
lines changed

_includes/timezone_converter.html

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,55 @@
3232
}
3333
}
3434
}
35+
function changeFormat() {
36+
const elems = document.getElementsByClassName("time");
37+
for (let i = 0; i < elems.length; i++) {
38+
const elem = elems[i];
39+
const timeText = elem.innerHTML;
40+
const [newTime, curFormat] = getNewFormat(timeText, elem.dataset.timeformat);
41+
elem.innerHTML = newTime;
42+
elem.dataset.timeformat = curFormat;
43+
}
44+
}
45+
46+
function getNewFormat(timeString, curFormat) {
47+
/*
48+
If curFormat is 12hr -> change to 24hr and vice versa
49+
*/
50+
const re = /(\d?\d:\d\d)(am|pm|AM|PM)?( \(next day\))?/;
51+
const parsed = timeString.match(re);
52+
if (parsed) {
53+
const hourMinArray = parsed[1].split(":");
54+
let hour = parseInt(hourMinArray[0]);
55+
let postfix = "";
56+
57+
if (parsed[2] || curFormat === "12hr") {
58+
if (parsed[2] && parsed[2].toLowerCase() === "pm") {
59+
if (hour !== 12)
60+
hour += 12;
61+
}
62+
curFormat = "24hr";
63+
}
64+
else if (curFormat === "24hr") {
65+
if (hour === 24) {
66+
hour = 0;
67+
postfix = "am";
68+
}
69+
else if (hour === 12)
70+
postfix = "pm";
71+
else if (hour > 12) {
72+
hour -= 12;
73+
postfix = "pm";
74+
}
75+
else
76+
postfix = "am";
77+
curFormat = "12hr";
78+
}
79+
const hourString = hour.toString().padStart(2, '0');
80+
return [hourString + ":" + hourMinArray[1] + postfix, curFormat];
81+
}
82+
return [timeString, curFormat];
83+
}
3584

3685
/*
3786
Convert date time string into a format accepted by Date object

0 commit comments

Comments
 (0)