Skip to content

Commit 7ac53eb

Browse files
implemented Relative time(posted ago) in comments metadata
1 parent 0e06ed2 commit 7ac53eb

File tree

1 file changed

+18
-6
lines changed

1 file changed

+18
-6
lines changed

src/components/Comments.js

Lines changed: 18 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,23 @@ const toggleViewReplies = (viewRepliesToggled, setViewRepliesToggled, key) => {
3131
)
3232
}
3333

34+
const intervals = [
35+
{ label: 'year', seconds: 31536000 },
36+
{ label: 'month', seconds: 2592000 },
37+
{ label: 'day', seconds: 86400 },
38+
{ label: 'hour', seconds: 3600 },
39+
{ label: 'minute', seconds: 60 },
40+
{ label: 'second', seconds: 1 }
41+
]
42+
43+
function timeSince(creationDate) {
44+
const date = new Date(creationDate)
45+
const seconds = Math.floor((Date.now() - date.getTime()) / 1000)
46+
const interval = intervals.find((i) => i.seconds < seconds)
47+
const count = Math.floor(seconds / interval.seconds)
48+
return `${count} ${interval.label}${count !== 1 ? 's' : ''} ago`
49+
}
50+
3451
const Comments = (props) => {
3552
const { storyId } = props
3653

@@ -141,12 +158,7 @@ const Comments = (props) => {
141158
{data.user.username}
142159
</Link>
143160
<div className='metadata'>
144-
<div>
145-
{`${data.createdAt.slice(0, 10)} ${data.createdAt.slice(
146-
11,
147-
19
148-
)}`}
149-
</div>
161+
<div>{timeSince(data.createdAt)}</div>
150162
</div>
151163
<div dangerouslySetInnerHTML={{ __html: data.Comments }} />
152164
<div>

0 commit comments

Comments
 (0)