Created
February 14, 2022 21:19
-
-
Save yoosinpaddy/f34ab9f08f95de219ad3f2f3bea2a666 to your computer and use it in GitHub Desktop.
Get More friendly remaining time from date and time string in flutter
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
String getRemainingTime(String? deadline) { | |
String toRet = ""; | |
int remSecs = secondsBetween(DateTime.now(), DateTime.parse(deadline!)); | |
if (remSecs < 0) { | |
isUrgent=true; | |
toRet = "Overdue by "; | |
remSecs = remSecs * -1; | |
} | |
int mdays = (remSecs / 86400).truncate(); | |
int rdays = (remSecs % 86400).truncate(); | |
int mhrs = 0; | |
int rhrs = 0; | |
int mmins = 0; | |
int rmins = 0; | |
int msec = 0; | |
if (mdays > 0) { | |
mhrs = (rdays / 3600).truncate(); | |
rhrs = (rdays % 3600).truncate(); | |
Timer.periodic(const Duration(hours: 1), (Timer t) { | |
if (mounted) setState(() {}); | |
}); | |
toRet = "$toRet $mdays days $mhrs hrs"; | |
} else { | |
mhrs = (rdays / 3600).truncate(); | |
rhrs = (rdays % 3600).truncate(); | |
if (mhrs > 0) { | |
mmins = (rhrs / 60).truncate(); | |
rmins = (rhrs % 60).truncate(); | |
toRet = "$toRet $mhrs hrs $mmins mins"; | |
Timer.periodic(const Duration(minutes: 1), (Timer t) { | |
if (mounted) setState(() {}); | |
}); | |
} else { | |
mmins = (rhrs / 60).truncate(); | |
rmins = (rhrs % 60).truncate(); | |
msec = (rmins / 60).truncate(); | |
toRet = "$toRet $mmins mins $rmins secs"; | |
Timer.periodic(const Duration(seconds: 1), (Timer t) { | |
if (mounted) setState(() { | |
isUrgent=true; | |
}); | |
}); | |
} | |
} | |
return toRet; | |
} | |
int secondsBetween(DateTime from, DateTime to) { | |
// from = DateTime(from.year, from.month, from.day); | |
// to = DateTime(to.year, to.month, to.day); | |
return (to.difference(from).inSeconds).round(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
the deadline tested had the format YYYY-MM-dd HH:mm:ss