JavaScript date-fns with Studio
Follow these instructions to use date-fns with your JavaScript function.
This example is from the date-fns website.
Example:
import { format, formatDistance, formatRelative, subDays } from 'date-fns'
format(new Date(), "'Today is a' eeee")
//=> "Today is a Thursday"
formatDistance(subDays(new Date(), 3), new Date(), { addSuffix: true })
//=> "3 days ago"
formatRelative(subDays(new Date(), 3), new Date())
//=> "last Friday at 7:26 p.m."
Your JavaScript function should use the dateFns prefix.
Example:
dateFns.format(new Date(), "'Today is a' eeee")
//=> "Today is a Thursday"
dateFns.formatDistance(dateFns.subDays(new Date(), 3), new Date(), { addSuffix: true })
//=> "3 days ago"
dateFns.formatRelative(dateFns.subDays(new Date(), 3), new Date())
//=> "last Friday at 7:26 p.m."
The date-fns library has two sub-modules: locale and fp.
Example:
import { addYears, formatWithOptions } from 'date-fns/fp'
import { eo } from 'date-fns/locale'
const addFiveYears = addYears(5)
const dateToString = formatWithOptions({ locale: eo }, 'D MMMM YYYY')
const dates = [
new Date(2017, 0, 1),
new Date(2017, 1, 11),
new Date(2017, 6, 2)
]
const toUpper = arg => String(arg).toUpperCase()
const formattedDates = dates.map(addFiveYears).map(dateToString).map(toUpper)
//=> ['1 JANUARO 2022', '11 FEBRUARO 2022', '2 JULIO 2022']
Your JavaScript function should use the dateFnsLocale prefix to access the locale sub-module and the dateFnsFp prefix to access the fp sub-module.
Example:
const addFiveYears = dateFnsFp.addYears(5)
const dateToString = dateFnsFp.formatWithOptions({ locale: dateFnsLocale.eo }, 'D MMMM YYYY')
const dates = [
new Date(2017, 0, 1),
new Date(2017, 1, 11),
new Date(2017, 6, 2)
]
const toUpper = arg => String(arg).toUpperCase()
const formattedDates = dates.map(addFiveYears).map(dateToString).map(toUpper)
//=> ['1 JANUARO 2022', '11 FEBRUARO 2022', '2 JULIO 2022']