Skip to content

Instantly share code, notes, and snippets.

@WebMaestroFr
Last active August 6, 2019 09:18
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 WebMaestroFr/dc75df7ff1fd9f78a081cf1c58fd17a8 to your computer and use it in GitHub Desktop.
Save WebMaestroFr/dc75df7ff1fd9f78a081cf1c58fd17a8 to your computer and use it in GitHub Desktop.
A React component to display timestamps as "time ago" strings.
import React, {Component} from 'react';
const SECOND = 1000,
MINUTE = SECOND * 60,
HOUR = MINUTE * 60,
DAY = HOUR * 24,
MONTH = DAY * 30,
YEAR = DAY * 365;
export const getTimeAgoString = (timestamp) => {
const elapsed = Date.now() - timestamp,
getElapsedString = (value, unit) => {
const round = Math.round(elapsed / value);
return `${round} ${unit}${round > 1
? 's'
: ''} ago`;
};
if (elapsed < MINUTE) {
return getElapsedString(SECOND, 'second');
}
if (elapsed < HOUR) {
return getElapsedString(MINUTE, 'minute');
}
if (elapsed < DAY) {
return getElapsedString(HOUR, 'hour');
}
if (elapsed < MONTH) {
return getElapsedString(DAY, 'day');
}
if (elapsed < YEAR) {
return getElapsedString(MONTH, 'month');
}
return getElapsedString(YEAR, 'year');
};
export default class TimeAgo extends Component {
state = {
datetime: null,
string: ""
};
setDateTime = ({timestamp}) => {
const date = new Date(timestamp);
this.setState({datetime: date.toISOString(), string: getTimeAgoString(timestamp)});
};
componentDidMount() {
this.setDateTime(this.props);
}
componentWillReceiveProps(props) {
this.setDateTime(props);
}
shouldComponentUpdate(props, {datetime}) {
return datetime !== this.state.datetime;
}
render() {
const {datetime, string} = this.state;
return <time dateTime={datetime}>{string}</time>;
}
}
@Isaac1m
Copy link

Isaac1m commented Nov 6, 2018

Found this helpful, thanks! Might want to change the prop validation for timestamp to

TimeAgo.propTypes = {
    timestamp: PropTypes.instanceOf(Date).isRequired
};

@adrihle
Copy link

adrihle commented Jul 13, 2019

Wonderfull mate. im starting with react and i have a doubt,

i passed the props like timestamp, directly fetched from mysql default timestamp, but appear a error of type string, how can i do for do it correctly? thanks!

@WebMaestroFr
Copy link
Author

WebMaestroFr commented Aug 6, 2019

Hi @Isaac1m, hi @adrihle,
Sorry for the very late reply, I haven't been on GitHub much lately.

Actually, the timestamp prop could be any accepted argument of a Date instance (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date). I'll skip the prop validation for now, until I find some time to tune it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment