{

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. DateTime.parse() method creates DateTime object using 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
THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.





Related posts

Dart| Flutter How to: Read pubspec.yaml attributes (version) with examples

How to Create and build a Singleton Class Dart or Flutter example| Dart By Example

What is the difference between var and dynamic and final in dart?| Flutter By Example

How to: Check if Phone number is valid or not in Dart| Flutter By Example

Dart| Flutter How to read an image from a disk and resize a file

Dart/Flutter: How to write setter and getter fields or members variables in a class with Example

Dart| Flutter How to get extension name and MIME type of a file with example