Created
March 2, 2018 19:08
-
-
Save goldhand/47a487319ac729f41f9cd59ab771468a to your computer and use it in GitHub Desktop.
Display a Date object react component
This file contains hidden or 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
/** | |
* Create a uniform appearance for date and time displays | |
* @module {Function} components/DateDisplay | |
* @flow | |
*/ | |
import * as React from 'react'; | |
import typeOf from 'ramda/src/type'; | |
const createDateDisplay = (getDisplay: (Date) => string, name: string) => { | |
const DateDisplay = ({ | |
date, | |
}: { | |
date: Date | string | number, | |
}): React.Node => { | |
let dateDisplay = date; | |
if (typeOf(date) === 'Number') { | |
dateDisplay = (new Date(dateDisplay): Date); | |
} | |
if (dateDisplay instanceof Date) { | |
dateDisplay = (getDisplay(dateDisplay): string); | |
} | |
return dateDisplay; | |
}; | |
DateDisplay.displayName = name; | |
return DateDisplay; | |
}; | |
/** | |
* Displays a date | |
* @param {Date|string|number} $0.date - a date, string or timestamp to display | |
* @returns {React.Node} <DateDisplay /> | |
*/ | |
export const DateDisplay = createDateDisplay(date => date.toLocaleDateString(), 'DateDisplay'); | |
/** | |
* Displays a time | |
* @param {Date|string|number} $0.date - a date, string or timestamp to display | |
* @returns {React.Node} <DateDisplay /> | |
*/ | |
export const TimeDisplay = createDateDisplay(date => date.toLocaleTimeString(), 'TimeDisplay'); | |
/** | |
* Displays a date and time | |
* @param {Date|string|number} $0.date - a date, string or timestamp to display | |
* @returns {React.Node} <DateDisplay /> | |
*/ | |
const DateTimeDisplay = createDateDisplay(date => date.toLocaleString(), 'DateTimeDisplay'); | |
DateTimeDisplay.Date = DateDisplay; | |
DateTimeDisplay.Time = TimeDisplay; | |
export default DateTimeDisplay; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment