-
-
Save i-like-robots/96ee63eb514934ce1d2f84bc39e4efc3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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