@@ -34,19 +34,22 @@ export function formatAsCurrency(x: number): string {
34
34
* @returns
35
35
*/
36
36
export function timeAgo ( date : Date , locale = "en-US" ) {
37
+ /** Difference in seconds */
37
38
const difference = ( new Date ( ) . getTime ( ) - date . getTime ( ) ) / 1000 ;
38
- const minutes = Math . floor ( difference / 60 ) ;
39
- const hours = Math . floor ( minutes / 60 ) ;
40
- const days = Math . floor ( hours / 24 ) ;
41
- const months = Math . floor ( days / 30 ) ;
42
- const years = Math . floor ( months / 12 ) ;
39
+ const minutes = difference / 60 ;
40
+ const hours = minutes / 60 ;
41
+ const days = hours / 24 ;
42
+ const months = days / 30 ;
43
+ const years = months / 12 ;
43
44
const relative = new Intl . RelativeTimeFormat ( locale , { numeric : "auto" } ) ;
45
+ // Use absolute value before rounding
46
+ const moreThan = ( v : number ) => Math . floor ( Math . abs ( v ) ) > 0 ;
44
47
45
- if ( years > 0 ) return relative . format ( 0 - years , "year" ) ;
46
- else if ( months > 0 ) return relative . format ( 0 - months , "month" ) ;
47
- else if ( days > 0 ) return relative . format ( 0 - days , "day" ) ;
48
- else if ( hours > 0 ) return relative . format ( 0 - hours , "hour" ) ;
49
- else if ( minutes > 0 ) return relative . format ( 0 - minutes , "minute" ) ;
48
+ if ( moreThan ( years ) ) return relative . format ( 0 - Math . floor ( years ) , "year" ) ;
49
+ else if ( moreThan ( months ) ) return relative . format ( 0 - Math . floor ( months ) , "month" ) ;
50
+ else if ( moreThan ( days ) ) return relative . format ( 0 - Math . floor ( days ) , "day" ) ;
51
+ else if ( moreThan ( hours ) ) return relative . format ( 0 - Math . floor ( hours ) , "hour" ) ;
52
+ else if ( moreThan ( minutes ) ) return relative . format ( 0 - Math . floor ( minutes ) , "minute" ) ;
50
53
51
54
return relative . format ( 0 - difference , "second" ) ;
52
55
}
0 commit comments