Skip to content

Instantly share code, notes, and snippets.

@c7x43t
Last active August 20, 2025 14:46
Show Gist options
  • Select an option

  • Save c7x43t/c3bc46b05e622ef508ff80a3c496801d to your computer and use it in GitHub Desktop.

Select an option

Save c7x43t/c3bc46b05e622ef508ff80a3c496801d to your computer and use it in GitHub Desktop.
// Efficient functions that serialize to and parse from this format:
// "YYYY-MM-DD HH:mm:ss"
function formatUTC(date) {
const y = date.getUTCFullYear();
const m = date.getUTCMonth() + 1;
const d = date.getUTCDate();
const H = date.getUTCHours();
const M = date.getUTCMinutes();
const S = date.getUTCSeconds();
return (
y + "-" +
(m < 10 ? "0" : "") + m + "-" +
(d < 10 ? "0" : "") + d + " " +
(H < 10 ? "0" : "") + H + ":" +
(M < 10 ? "0" : "") + M + ":" +
(S < 10 ? "0" : "") + S
);
}
// Read 2 and 4 digits without creating substrings
const d2 = (i,s) => (s.charCodeAt(i) - 48) * 10 + (s.charCodeAt(i + 1) - 48);
const d4 = (i,s) =>
(s.charCodeAt(i) - 48) * 1000 +
(s.charCodeAt(i + 1) - 48) * 100 +
(s.charCodeAt(i + 2) - 48) * 10 +
s.charCodeAt(i + 3) - 48;
// assumes exact format "YYYY-MM-DD HH:mm:ss"
function parseUTC_yyyyMMdd_HHmmss(s) {
// Quick delimiter checks (cheap, helps avoid misparsing)
if (s.length !== 19 ||
s.charCodeAt(4) !== 45 || // -
s.charCodeAt(7) !== 45 || // -
s.charCodeAt(10) !== 32 || // space
s.charCodeAt(13) !== 58 || // :
s.charCodeAt(16) !== 58) // :
return null; // or throw
const year = d4(0,s);
const month = d2(5,s); // 1–12
const day = d2(8,s); // 1–31 (rough check optional)
const hour = d2(11,s); // 0–23
const min = d2(14,s); // 0–59
const sec = d2(17,s); // 0–59
// Optional light range checks (skip if you want every last ns)
if (month < 1 || month > 12 || day < 1 || day > 31 ||
hour > 23 || min > 59 || sec > 59) return null;
// Construct as UTC
return new Date(Date.UTC(year, month - 1, day, hour, min, sec));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment