Created with <3 with dartpad.dev.
Created
January 26, 2024 03:07
-
-
Save mvfsillva/11abe4751c3dee33dd41cf62a7a96293 to your computer and use it in GitHub Desktop.
sparkling-snowflake-9107
This file contains hidden or 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
| 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