Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save manthri-mohan-sai/c9ce2411ac36cab0a6f4e96c371d8717 to your computer and use it in GitHub Desktop.
Save manthri-mohan-sai/c9ce2411ac36cab0a6f4e96c371d8717 to your computer and use it in GitHub Desktop.
A descriptive datetime extension
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
}
@manthri-mohan-sai
Copy link
Author

Run in: Dartpad

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment