skip to Main Content

I’m new to flutter. In my app I have a button which onPressed shows a timepicker. I want to set the title of the button to the time selected by user in this format: 2:30 PM. To do that I need to format the time. I’m using the intl package but can’t seem to figure out how to use it to format the time. Here’s the code:

import 'package:flutter/material.dart';
import 'package:intl/intl.dart';

class ShowTimePickerWidget extends StatefulWidget {
  const ShowTimePickerWidget({super.key});

  @override
  State<ShowTimePickerWidget> createState() => _ShowTimePickerWidgetState();
}

class _ShowTimePickerWidgetState extends State<ShowTimePickerWidget> {
  TimeOfDay? selectedTime;

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        const Icon(Icons.access_time),
        Expanded(
          child: TextButton(
            onPressed: () async {
              TimeOfDay time = TimeOfDay.now();
              final pickedTime = await showTimePicker(
                context: context,
                initialTime: time,
              );
              setState(() {
                selectedTime = pickedTime;
              });
            },
            child: Text(
              (selectedTime == null)
                  ? 'Time to start your day'
                  : //set the formatted time string here,
            ),
          ),
        ),
      ],
    );
  }
}

intl version: 0.18.1

2

Answers


  1. final TimeOfDay? timePicked = await showTimePicker(
          context: context,
          initialTime: TimeOfDay.now(),
        );
        if (timePicked != null)
          setState(() {
            _selectedTime = timePicked;
          });
        // Conversion logic starts here
        DateTime tempDate = DateFormat("hh:mm").parse(
            _selectedTime!.hour.toString() +
                ":" + _selectedTime!.minute.toString());
        var dateFormat = DateFormat("h:mm a"); // you can change the format here
        print(dateFormat.format(tempDate))
    
    Login or Signup to reply.
  2. I think this is what you need, if not, please let me know and I will provide more support.

    Happy coding!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search