Skip to content

Instantly share code, notes, and snippets.

@bradmarshall
Last active August 24, 2022 19:33
Show Gist options
  • Save bradmarshall/a63ac0b9e3777ba93b61ab94855eb245 to your computer and use it in GitHub Desktop.
Save bradmarshall/a63ac0b9e3777ba93b61ab94855eb245 to your computer and use it in GitHub Desktop.
Format a date string or date object using DayJS
import dayjs from 'dayjs'
// @param date {string, dayjs object}
// @param separator {string} optional - separates year/month/day numbers. Empty string is valid.
function formatDateAsYearMonthDay(date, separator = '-') {
if (!(date instanceof dayjs || typeof date === 'string')) {
return false // Unsupported date type. `undefined` is unsupported.
}
const parsedDate = date instanceof dayjs
? date
: dayjs(date)
if (parsedDate.isValid()) {
return parsedDate.format(`YYYY${separator}MM${separator}DD`)
}
return false // date could not be parsed.
}
export default formatDateAsYearMonthDay
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment