TimeToCode
TimeToCode

Reputation: 1838

how to add seconds in picked time

i am using showTimePicker widget to pick time, when i select the time , it prints it like this 7:10 PM but i want to add seconds too, it should be like 7:10:00 PM seconds can be default 00.

here is my code where i am creating this

 TextField(
        decoration: InputDecoration(labelText: timein,hintText: "Time in",icon: Icon(Icons.timer)),
        controller:timeinController ,
        readOnly:true,
        onTap: () async {
                  TimeOfDay pickedTime =  await showTimePicker(
                          initialTime: TimeOfDay.now(),
                          context: context,
                      );
        if(pickedTime != null ){
                      print(pickedTime.format(context));   //output 7:10 PM
                      setState(() {
                        timeinController.text = pickedTime.format(context);  //set the value of text field. 
                      });
                  }else{
                      print("Time is not selected");
                  }
                },
      ),

here showtimepicker looks like

enter image description here

please help how to do this.

Upvotes: 2

Views: 2414

Answers (1)

JideGuru
JideGuru

Reputation: 7660

TimeOfDay does not include seconds but DateTime provides it so you can get the second from DateTime and append it to TimeOfDay like below.

      TextField(
              decoration: InputDecoration(labelText: 'Time in',hintText: "Time in",icon: Icon(Icons.timer)),
              // controller: timeinController ,
              readOnly:true,
              onTap: () async {
                TimeOfDay? pickedTime =  await showTimePicker(
                  initialTime: TimeOfDay.now(),
                  context: context,
                );
                if(pickedTime != null ){
                  DateTime date = DateTime.now();
                  String second = date.second.toString().padLeft(2, '0');
                  List timeSplit = pickedTime.format(context).split(' ');
                  String formattedTime = timeSplit[0];
                  String time = '$formattedTime:$second';
                  String type = '';
                  if(timeSplit.length > 1) {
                    type = timeSplit[1];
                    time = '$time $type';
                  }

                  print(time); //output 7:10:00 PM
                  setState(() {
                    timeinController.text = pickedTime.format(context);  //set the value of text field.
                  });
                }else{
                  print("Time is not selected");
                }
              },
            )

Upvotes: 1

Related Questions