Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@goldhand
Created March 2, 2018 19:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save goldhand/47a487319ac729f41f9cd59ab771468a to your computer and use it in GitHub Desktop.
Save goldhand/47a487319ac729f41f9cd59ab771468a to your computer and use it in GitHub Desktop.
Display a Date object react component
/**
* 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