I am creating an app where i want to show ‘today’ and ‘yesterday’ instead of date
i have created this method but looks code is lengthy..
is there any other better way to make more advance level code? and is this code ok for it?
String? getDateAsString(DateTime date) {
String result = '';
DateTime today = DateTime.now();
print(today.toString());
DateTime yesterday = DateTime.now().subtract(Duration(days: 1));
print(yesterday.toString());
if (date.year == today.year &&
date.month == today.month &&
date.day == today.day) {
result = 'Today';
} else {
if (date.year == yesterday.year &&
date.month == yesterday.month &&
date.day == yesterday.day) {
result = 'Yesterday';
} else {
result = DateFormat.MMMEd().format(date);
}
}
return result;
}
void main() {
DateTime date = DateTime(2023, 08, 12);
print(getDateAsString(date));
}
2
Answers
Here’s your solution.
Source code:
Execution code