Skip to content

Instantly share code, notes, and snippets.

@i-like-robots
Last active March 16, 2024 19:33
Show Gist options
  • Save i-like-robots/96ee63eb514934ce1d2f84bc39e4efc3 to your computer and use it in GitHub Desktop.
Save i-like-robots/96ee63eb514934ce1d2f84bc39e4efc3 to your computer and use it in GitHub Desktop.
const MATCH = /^(-|\+)([1-9][0-9]{0,2})(h|d|w|m|y)(\/d)?$/
const isDateMathExpression = (dateStr) => {
return typeof dateStr === 'string' && MATCH.test(dateStr)
}
const parseDateMathExpression = (dateStr) => {
const [match, operator, number, unit, round] = MATCH.exec(dateStr) || []
if (match) {
const factor = operator === '-' ? -1 : 1
const value = parseInt(number, 10) * factor
let date = new Date()
if (round) {
date = new Date(date.toISOString().slice(0, 10))
}
switch (unit) {
case 'h':
date.setHours(date.getHours() + value)
break
case 'd':
date.setDate(date.getDate() + value)
break
case 'w':
date.setDate(date.getDate() + (value * 7))
break
case 'm':
date.setMonth(date.getMonth() + value)
break
case 'y':
date.setFullYear(date.getFullYear() + value)
break
}
return date
}
}
console.log('Addition:')
console.log(parseDateMathExpression('+1h'))
console.log(parseDateMathExpression('+1d/d'))
console.log(parseDateMathExpression('+1w/d'))
console.log(parseDateMathExpression('+1m/d'))
console.log(parseDateMathExpression('+1y/d'))
console.log('Subtraction:')
console.log(parseDateMathExpression('-1h'))
console.log(parseDateMathExpression('-1d/d'))
console.log(parseDateMathExpression('-1w/d'))
console.log(parseDateMathExpression('-1m/d'))
console.log(parseDateMathExpression('-1y/d'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment