Skip to content

Instantly share code, notes, and snippets.

@mvfsillva
Created January 26, 2024 03:07
Show Gist options
  • Select an option

  • Save mvfsillva/11abe4751c3dee33dd41cf62a7a96293 to your computer and use it in GitHub Desktop.

Select an option

Save mvfsillva/11abe4751c3dee33dd41cf62a7a96293 to your computer and use it in GitHub Desktop.
sparkling-snowflake-9107

sparkling-snowflake-9107

Created with <3 with dartpad.dev.

String calculateAge(DateTime birthdate) {
DateTime currentDate = DateTime.now();
Duration difference = currentDate.difference(birthdate);
int years = (difference.inDays / 365.25).floor();
DateTime birthdateCopy =
DateTime(birthdate.year, birthdate.month, birthdate.day);
birthdateCopy = DateTime(currentDate.year, birthdate.month, birthdate.day);
bool isBeforeBirthdate = currentDate.isBefore(birthdateCopy);
bool isSameMonthAndEarlierDay = currentDate.month == birthdateCopy.month &&
currentDate.day < birthdateCopy.day;
int months = currentDate.month - birthdateCopy.month;
if (isBeforeBirthdate || isSameMonthAndEarlierDay) {
months = 12 - months.abs();
}
int days = currentDate.day - birthdate.day;
return '$years years, $months months, $days days';
}
void main() {
DateTime birthdate = DateTime(2023, 9, 27);
print(calculateAge(birthdate));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment