Home > Software engineering >  How to format Time in Flutter
How to format Time in Flutter

Time:03-06

I have the following function, where within a ListBody I map List values, I have a time parameter that returns a time. This contains unnecessary digits and I want to format it.

In other normal List situations I use the function

    var timeFormat = DateFormat("HH:mm");
    String timetest = timeFormat.format(my_data);

How can I implement my above function to format the time in the below RichText, where I enter data into TextSpan from the map, and cannot build it as a var outside and then call it in?

var mappedValues = ListBody(
    children: [...mappedList.map((m) => RichText (
       text: TextSpan( 
              children: <TextSpan> [
       
              TextSpan(text: m.time!.toLocal().toString(), style: TextStyle(
              fontSize: 18 ,
              fontWeight: FontWeight.w400, 
              color: Color(0xff2F2F2F),
              fontFamily: 'DMSans'
               )
              ),
            ]
    )))]);

Thank you

Update

Example of initial output

    2022-03-05 23:24:00.000

My function will turn it to

    23:24

CodePudding user response:

Then you should be able to create a method within this widget that takes the Datetime (m.time) as input and returns the formatted time, as:

String getFormattedTime(DateTime time) {

 var timeFormat = DateFormat("HH:mm");
 String timePortion = timeFormat.format(time);
 return timePortion;
}

Then inside your widget just call it:

TextSpan(text: getFormattedTime(m.time!))

You could also move this method into a common utility class so you can reuse it throughout your app. Let me know if that’s what you looking for and works for your purposes.

Check out this enter image description here

Let me know if that's clear.

  • Related