Skip to content

Instantly share code, notes, and snippets.

@tamouse
Last active June 5, 2019 12:56
Show Gist options
  • Save tamouse/5f1efbe8ce778bd6705d5eae35f3590b to your computer and use it in GitHub Desktop.
Save tamouse/5f1efbe8ce778bd6705d5eae35f3590b to your computer and use it in GitHub Desktop.
A React Time atom, that uses date-fns
import React from "react"
import T from "prop-types"
import { format, parse } from "date-fns"
/**
* Time
*
* @function
*
* @see https://date-fns.org/v1.30.1/docs/format for string formats
*/
export const Time = ({ value, format: formatString, ...timeProps }) => {
const parsedValue = parse(value)
return (
<time value={parsedValue.toISOString()} {...timeProps}>
{format(parsedValue, formatString)}
</time>
)
}
Time.propTypes = {
/**
* The value of time to display. Should be in ISO8601 format, but must be parsable by
* date-fns's `parse` method. Allows numeric values for epoc seconds or milliseconds.
*/
value: T.oneOfType([T.string, T.number]).isRequired,
/**
* format of the time, defaults to "MMMM Do, YYYY" (January 1st, 2019). Represented
* internally as `formatString` to prevent a collision with date-fns's `format` method.
*/
format: T.string,
}
Time.defaultProps = {
format: "MMMM Do, YYYY",
}
export default Time
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment