Let’s take look look at the code. The below code helps to convert time to human readable time with correct format.
It helps to convert time from Firebase to human readable time format. It can auto detect if we need to show the time in seconds, minutes or hours.
Here you may also DateTime to duTimeLineFormat() function. It will return the difference based on the current time.
I have used this in chat app. Chat app requires advanced time difference.
String timeFormated(String? time) {
final DateTime now =
time == null ? DateTime.now().toLocal() : DateTime.parse(time).toLocal();
final DateFormat formatter =
DateFormat('yyyy-MM-dd HH:mm:ss', Platform.localeName);
return formatter.format(now);
}
String duTimeLineFormat(DateTime dt) {
var now = DateTime.now();
var difference = now.difference(dt);
if (difference.inSeconds < 60) {
if (difference.inSeconds < 0) {
return "0s ago";
}
return "${difference.inSeconds}s ago";
}
if (difference.inMinutes < 60) {
return "${difference.inMinutes}m ago";
}
if (difference.inHours < 24) {
return "${difference.inHours}h ago";
} else if (difference.inDays < 30) {
return "${difference.inDays}d ago";
}
// MM-dd
else if (difference.inDays < 365) {
final dtFormat = new DateFormat('MM-dd', Platform.localeName);
return dtFormat.format(dt);
}
// yyyy-MM-dd
else {
final dtFormat = new DateFormat('yyyy-MM-dd', Platform.localeName);
var str = dtFormat.format(dt);
return str;
}
}
If you pass a DateTime object, it will work on it’s own. First it creates a time difference between a current time and given time object.
and then it returns exact difference between the two times in human readable manner.