Search code examples
flutterdart

I have a String like this "6:45AM" then how can i convert it into 24-hour TimeOfDay or DateTime format


I want to convert a string (12 hour) "6:45PM" into a 18:45:00 (24 hour) TimeOfDay Format, how can be this done?


Solution

  • You can try to use a DateFormat, just include intl dependency to your pubspec.yaml

    First parse the value to a date, then format it how you want

    import 'package:intl/intl.dart';
    // parse date
    DateTime date= DateFormat.jm().parse("6:45 PM");
    DateTime date2= DateFormat("hh:mma").parse("6:45PM"); // think this will work better for you
    // format date
    print(DateFormat("HH:mm").format(date));
    print(DateFormat("HH:mm").format(date2));
    

    References