Dart| Flutter: How to Convert timestamp string from 24 hours to 12-hour format| Flutter By Example

By default, the DateTime object returns the date and time, time contains a 24-hour format.

This tutorial shows how to convert the String of date and time into a DateTime class object in dart and flutter.

How to convert time string from 24 hours to 12-hour format in Dart

For example, a String contains a date formatted string - 2022-05-20 23:12:20.000. The DateTime.parse() method creates a DateTime object using a formatted string.

DateTime parse(String formattedString)

formattedString is an ISO string format.

Next, use intl dependency

First, Add the intl dependency to pubspec.yaml

dev_dependencies:
    intl: any

Next, Import the intl package in the dart code file

import 'package:intl/intl.dart';

Create a DateFormat with 12 hour format from the intl package. Here is an example program

import 'package:intl/intl.dart';

void main() {
  var strDate = '2022-05-20 23:12:20.000';
  try {
    final dateFormat = DateFormat('h:mm a');

    final stringFormat = dateFormat.format(DateTime.parse(strDate));
    print(stringFormat);
    print(stringFormat.runtimeType);
  } on Exception catch (exception) {
    print(exception);
  }
}

Output:

11:12 PM
String