2018-09-03 16:17:36 +02:00
|
|
|
//@flow
|
|
|
|
|
import React from "react";
|
|
|
|
|
import { translate } from "react-i18next";
|
2019-10-09 15:51:49 +02:00
|
|
|
import { formatDistance, format, parseISO } from "date-fns";
|
|
|
|
|
import { enUS, de, es } from "date-fns/locale";
|
2019-10-08 16:42:08 +02:00
|
|
|
import styled from "styled-components";
|
2019-02-07 09:28:43 +01:00
|
|
|
|
2019-10-09 15:51:49 +02:00
|
|
|
const supportedLocales = {
|
|
|
|
|
enUS,
|
|
|
|
|
de,
|
|
|
|
|
es
|
|
|
|
|
};
|
2019-03-12 10:44:58 +01:00
|
|
|
|
2018-09-03 16:17:36 +02:00
|
|
|
type Props = {
|
|
|
|
|
date?: string,
|
|
|
|
|
|
|
|
|
|
// context props
|
|
|
|
|
i18n: any
|
|
|
|
|
};
|
|
|
|
|
|
2019-10-09 15:51:49 +02:00
|
|
|
const DateElement = styled.time`
|
2019-10-08 16:42:08 +02:00
|
|
|
border-bottom: 1px dotted rgba(219, 219, 219);
|
|
|
|
|
cursor: help;
|
|
|
|
|
`;
|
2018-09-03 16:17:36 +02:00
|
|
|
|
2019-10-08 16:42:08 +02:00
|
|
|
class DateFromNow extends React.Component<Props> {
|
2019-10-09 15:51:49 +02:00
|
|
|
getLocale = () => {
|
|
|
|
|
const { i18n } = this.props;
|
|
|
|
|
const locale = supportedLocales[i18n.language];
|
|
|
|
|
if (!locale) {
|
|
|
|
|
return enUS;
|
|
|
|
|
}
|
|
|
|
|
return locale;
|
|
|
|
|
};
|
2019-02-07 09:28:43 +01:00
|
|
|
|
2019-10-09 15:51:49 +02:00
|
|
|
createOptions = () => {
|
|
|
|
|
const locale = this.getLocale();
|
|
|
|
|
return {
|
|
|
|
|
locale
|
|
|
|
|
};
|
|
|
|
|
};
|
2019-02-07 09:28:43 +01:00
|
|
|
|
2019-10-09 15:51:49 +02:00
|
|
|
render() {
|
|
|
|
|
const { date } = this.props;
|
|
|
|
|
if (date) {
|
|
|
|
|
const isoDate = parseISO(date);
|
|
|
|
|
const options = this.createOptions();
|
|
|
|
|
const distance = formatDistance(isoDate, new Date(), options);
|
|
|
|
|
const formatted = format(isoDate, "yyyy-MM-dd HH:mm:ss", options);
|
|
|
|
|
return <DateElement title={formatted}>{distance}</DateElement>;
|
2019-02-07 09:28:43 +01:00
|
|
|
}
|
|
|
|
|
return null;
|
2018-09-03 16:17:36 +02:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2019-10-08 16:42:08 +02:00
|
|
|
export default translate()(DateFromNow);
|