skip to Main Content

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


  1. Here’s your solution.

    Source code:

    String dateTimeFunction({required DateTime dateTime}) {
      final DateTime dtToday = DateTime.now();
      final DateTime dtYesterday = DateTime.now().subtract(const Duration(days: 1));
      final DateFormat formatter = DateFormat("dd-MM-yyyy");
    
      return formatter.format(dateTime) == formatter.format(dtToday)
          ? "Hey it's Today ${formatter.format(dtToday)}"
          : formatter.format(dateTime) == formatter.format(dtYesterday)
              ? "Hey it's Yesterday ${formatter.format(dtYesterday)}"
              : "Hey it's Unknown ${formatter.format(dateTime)}";
    }
    

    Execution code

    print(dateTimeFunction(dateTime: DateTime(2023, 08, 29)));
    // Output: Hey it's Today 29-08-2023
    
    print(dateTimeFunction(dateTime: DateTime(2023, 08, 28)));
    // Output: Hey it's Yesterday 28-08-2023
    
    print(dateTimeFunction(dateTime: DateTime(2023, 08, 27)));
    // Output: Hey it's Unknown 27-08-2023
    
    Login or Signup to reply.
  2. date.difference(DateTime.now()).inDays==0 // 0 for today and -1 for yesterday and 1 for tomorrow
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search