'Invalid date format Today

I'm trying to display time or date based on online. For example if the user is last online today at 15.00, then the time displayed is 15.00. And if the is last online yesterday/today then the time displayed is yesterday/today.

Here is the current time format:

enter image description here

Tried adding this code below to my ConversationModel.dart:

String getOnlyTime(){
 var time = DateTime.parse(date!);
 return "${time.hour}:${time.minute}";
}

And this code below to my ChatScreen.dart:

Text(conversion!.getOnlyTime())

Worked fine when the user's last online is time (e.g 15.00) but not when the user's last online is yesterday/today with this error:

enter image description here

'Today' is returned from this model class:

 ConversationModel objConversation = ConversationModel(
    id: query.find().first.id,
    idReceiver: contactList[index].userId,
    fullName: contactList[index].userName,
    image: '',
    date: 'Today',
    messageCout: count);
    idConversation = mains.objectbox.boxConversation.put(objConversation);

Any solutions?



Solution 1:[1]

you can do this way : As per your description date will be Today or Tomorrow or actual date string

try{
 var time = DateTime.parse(date!);
 return "${time.hour}:${time.minute}";
}catch(e) {
  return date!;
} 

Edited

String getOnlyTime(){
 try{
     var time = DateTime.parse(date!);
     return "${time.hour}:${time.minute}";
    }catch(e) {
      return date!;
    } 
}

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1