1+ import distanceInWordsToNow from 'date-fns/distance_in_words_to_now' ;
2+ import differenceInMilliseconds from 'date-fns/difference_in_milliseconds' ;
13import format from 'date-fns/format' ;
24import isValid from 'date-fns/is_valid' ;
35import parseISO from 'date-fns/parse' ;
6+ import i18next from 'i18next' ;
47
58function parse ( maybeDate ) {
69 const date = maybeDate instanceof Date ? maybeDate : parseISO ( maybeDate ) ;
@@ -13,6 +16,31 @@ function parse(maybeDate) {
1316}
1417
1518export default {
19+ distanceInWordsToNow ( date ) {
20+ const parsed = parse ( date ) ;
21+
22+ if ( parsed ) {
23+ const now = new Date ( ) ;
24+ const diffInMs = differenceInMilliseconds ( now , parsed ) ;
25+
26+ if ( Math . abs ( diffInMs < 10000 ) ) {
27+ return i18next . t ( 'formatDate.JustNow' ) ;
28+ } else if ( diffInMs < 20000 ) {
29+ return i18next . t ( 'formatDate.15Seconds' ) ;
30+ } else if ( diffInMs < 30000 ) {
31+ return i18next . t ( 'formatDate.25Seconds' ) ;
32+ } else if ( diffInMs < 46000 ) {
33+ return i18next . t ( 'formatDate.35Seconds' ) ;
34+ }
35+
36+ const timeAgo = distanceInWordsToNow ( parsed , {
37+ includeSeconds : true
38+ } ) ;
39+ return i18next . t ( 'formatDate.Ago' , { timeAgo } ) ;
40+ }
41+
42+ return '' ;
43+ } ,
1644 format ( date , { showTime = true } = { } ) {
1745 const parsed = parse ( date ) ;
1846 const formatType = showTime ? 'MMM D, YYYY h:mm A' : 'MMM D, YYYY' ;
0 commit comments