el_sas
el_sas

Reputation: 45

How to format a TimePicker to 24 hours. "00:00" Flutter

I want to apply formatting to a time that the TimePicker gives me, since it gives me 13:30, but when I want to print it I get 1:30 PM, and I want it to give me 13:30 only.

I attach the code of the _pickTime:

//Función que muestra el Time Picker.
  _pickTime() async {
    TimeOfDay? timeRecord = await showTimePicker(
      context: context,
      initialTime: time.replacing(hour: time.hourOfPeriod),
      
    );
    if (timeRecord != null) {
      setState(() {
        finaltime = time.format(context);
      });
    }
  }

Upvotes: 3

Views: 6089

Answers (3)

Kevinsom98
Kevinsom98

Reputation: 146

use intl package

         var df = DateFormat("h:mm a");
         var dt = df.parse(timeRecord!.format(context));
         print(DateFormat('HH:mm').format(dt));

so your function would look like

  _pickTime() async {
TimeOfDay? timeRecord = await showTimePicker(
  context: context,
  initialTime: time.replacing(hour: time.hourOfPeriod),
  
);
  if (timeRecord != null) {
  setState(() {
       var df = DateFormat("h:mm a");
       var dt = df.parse(timeRecord!.format(context));
       var finaltime =  DateFormat('HH:mm').format(dt); 
      //print(finaltime)  
      // this will return 13:30 only
  });
}

}

Upvotes: 5

Kerim
Kerim

Reputation: 578

Try this with intl.

    final dateNow = DateTime.now();
    final date = DateTime(dateNow.year, dateNow.month, dateNow.day, finalTime.hour,   
                   finalTime.minute);
    final timeStringFormatted = DateFormat(DateFormat.HOUR24_MINUTE)
                            .format(date);

Upvotes: 0

Indrajit Sharma
Indrajit Sharma

Reputation: 170

You can use intl package.

And use this before you print

DateFormat.jm().format(paste your yourdatetime here)

Upvotes: 0

Related Questions