at main 1.6 kB view raw
1/// DateTime utility functions 2/// 3/// Provides reusable time formatting and number formatting utilities. 4/// All functions accept current time as parameter to enable testing 5/// without relying on DateTime.now(). 6class DateTimeUtils { 7 // Private constructor to prevent instantiation 8 DateTimeUtils._(); 9 10 /// Format time difference as human-readable "ago" string 11 /// 12 /// Examples: 13 /// - Less than 60 minutes: "5m", "45m" 14 /// - Less than 24 hours: "2h", "23h" 15 /// - Less than 365 days: "5d", "364d" 16 /// - 365+ days: "1yr", "2yr" 17 /// 18 /// [dateTime] is the past time to format 19 /// [currentTime] is the reference time (defaults to now for production use) 20 static String formatTimeAgo(DateTime dateTime, {DateTime? currentTime}) { 21 final now = currentTime ?? DateTime.now(); 22 final difference = now.difference(dateTime); 23 24 if (difference.inMinutes < 60) { 25 return '${difference.inMinutes}m'; 26 } else if (difference.inHours < 24) { 27 return '${difference.inHours}h'; 28 } else if (difference.inDays < 365) { 29 return '${difference.inDays}d'; 30 } else { 31 final years = (difference.inDays / 365).floor(); 32 return '${years}yr'; 33 } 34 } 35 36 /// Format large numbers with 'k' suffix for thousands 37 /// 38 /// Examples: 39 /// - 0-999: "0", "42", "999" 40 /// - 1000+: "1.0k", "5.2k", "12.5k" 41 /// 42 /// [count] is the number to format 43 static String formatCount(int count) { 44 if (count < 1000) { 45 return count.toString(); 46 } else { 47 final thousands = count / 1000; 48 return '${thousands.toStringAsFixed(1)}k'; 49 } 50 } 51}