Skip to content

Instantly share code, notes, and snippets.

@alifhasnain
Created June 10, 2024 11:28
Show Gist options
  • Save alifhasnain/5d1761c9b0d6843771cdb881ec9ae550 to your computer and use it in GitHub Desktop.
Save alifhasnain/5d1761c9b0d6843771cdb881ec9ae550 to your computer and use it in GitHub Desktop.
void main() {
print(DateTime(2023, 6, 10).elapsed);
}
extension Elapsed on DateTime {
String get elapsed {
String result = "";
DateTime now = DateTime.now();
int years = now.year - this.year;
int months = now.month - this.month;
int days = now.day - this.day;
print("Now year: ${now.year}");
print("This year: ${this.year}");
print("Now months: ${now.month}");
print("This months: ${this.month}");
print("Now days: ${now.day}");
print("This days: ${this.day}");
if (days < 0) {
final previousMonth = DateTime(now.year, now.month - 1, this.day);
days = (now.difference(previousMonth).inDays);
months -= 1;
}
if (months < 0) {
months += 12;
years -= 1;
}
result = days > 0 ? "${days}d" : result;
result = months > 0 ? "${months}mo $result" : result;
result = years > 0 ? "${years}yr $result" : result;
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment