Created
June 1, 2023 02:23
-
-
Save manthri-mohan-sai/c9ce2411ac36cab0a6f4e96c371d8717 to your computer and use it in GitHub Desktop.
A descriptive datetime extension
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension DescribeDateTime on DateTime { | |
void describe() { | |
final now = DateTime.now(); | |
final difference = this.difference(DateTime(now.year, now.month, now.day)); | |
String description = switch (difference) { | |
Duration(inDays: 0) => 'today', | |
Duration(inDays: -1) => 'yesterday', | |
Duration(inDays: 1) => 'tomorrow', | |
Duration(inDays: int d, isNegative: false) => "$d days from now", | |
Duration(inDays: int d, isNegative: true) => "${d.abs()} days ago", | |
}; | |
print('$year/$month/$day is $description'); | |
} | |
} | |
void main() { | |
DateTime.now().describe(); // Should print 2023/6/1 is today | |
DateTime(2023, 5, 31).describe(); // Should print 2023/5/31 is yesterday | |
DateTime(2023, 5, 28).describe(); // Should print 2023/5/28 is 4 days ago | |
DateTime(2023, 6, 2).describe(); // Should print 2023/6/2 is tomorrow | |
DateTime(2023, 6, 30).describe(); // Should print 2023/6/30 is 29 days from now | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Run in: Dartpad