Skip to content

Instantly share code, notes, and snippets.

@Nixinova
Last active May 4, 2021 07:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Nixinova/a8b455392295443b111d30a943c75bb7 to your computer and use it in GitHub Desktop.
Save Nixinova/a8b455392295443b111d30a943c75bb7 to your computer and use it in GitHub Desktop.
Date normaliser: convert a prose date to ISO
function normalise(str, outSep = ',') {
const R = String.raw
const re = str => RegExp(
str.replace(/ /g, R`\s*`).replace(/-/g, r.sep).replace(/[DMY]/g, c => r[c.toLowerCase()]),
'g'
)
const monthsL = 'January February March April May June July August September October November December'.toLowerCase().split(' ')
const monthsS = monthsL.map(month => month.substr(0, 3))
const year = y => y.toString().padStart(4, '0')
const month = m => (m.length > 3 ? monthsL.indexOf(m) + 1 : monthsS.indexOf(m) + 1).toString().padStart(2, '0')
const day = d => d.toString().padStart(2, '0')
const ymd = (y, m, d) => `${year(y)}-${month(m.toLowerCase())}-${day(d)}`
const ymd2 = (a, b) => [ymd(...a), ymd(...b)].join(outSep)
const r = {
d: R`(\d{1,2})`,
m: R`([A-Za-z]{3,})`,
y: R`(\d{4})`,
sep: R`[-–—]`,
}
let output = str
.replace(re('D M Y - D M Y'), (_, d1, m1, y1, d2, m2, y2) => ymd2([y1, m1, d1], [y2, m2, d2])) // '01 Jan 2000 - 01 Jan 2001'
.replace(re('M D,? Y - M D,? Y'), (_, d1, m1, y1, d2, m2, y2) => ymd2([y1, m1, d1], [y2, m2, d2])) // 'Jan 01, 2000 - Jan 01, 2001'
.replace(re('D M - D M Y'), (_, d1, m1, d2, m2, y) => ymd2([y, m1, d1], [y, m2, d2])) // '01 Jan - 01 Feb 2000'
.replace(re('M D - M D,? Y'), (_, d1, m1, d2, m2, y) => ymd2([y, m1, d1], [y, m2, d2])) // 'Jan 01 - Feb 01, 2000'
.replace(re('D - D M Y'), (_, d1, d2, m, y) => ymd2([y, m, d1], [y, m, d2])) // '01-02 Jan 2000'
.replace(re('M D - D,? Y'), (_, d1, d2, m, y) => ymd2([y, m, d1], [y, m, d2])) // 'Jan 01-02, 2000'
.replace(re('D M Y'), (_, d, m, y) => ymd(y, m, d)) // '01 Jan 2000'
.replace(re('M D,? Y'), (_, d, m, y) => ymd(y, m, d)) // 'Jan 01, 2000'
.replace(re('M Y'), (_, m, y) => ymd(y, m, '0')) // 'Jan 2000'
return output;
}
if (typeof module !== 'undefined') {
module.exports = normalise
const arg = process.argv[n + 1] || ''
if (arg(1)) console.log(normalise(arg(1)))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment