How to Format DateTime in Flutter

How to Format DateTime in Flutter

19 December 2024 Stephan Petzl Leave a comment Tech-Help

Displaying the current DateTime in a Flutter application can be straightforward, but formatting it to meet specific needs often requires additional steps. This guide will walk you through the process of formatting a DateTime object in Flutter, using a popular and efficient method.

Problem Statement

When displaying the current DateTime, you might encounter unwanted details such as milliseconds. For example, you may see a format like “YYYY-MM-DD HH-MM:00.000” and wish to remove the “:00.000” part.

Solution

One of the most effective ways to format DateTime in Flutter is by using the intl package. This package provides robust capabilities for formatting dates and times in a variety of ways.

Steps to Format DateTime

  1. Add the intl package to your pubspec.yaml file:
    dependencies:
      flutter:
        sdk: flutter
      intl: ^0.16.1
    
  2. Import the package in your Dart code:
    import 'package:intl/intl.dart';
  3. Format the DateTime object:
    DateTime now = DateTime.now();
    String formattedDate = DateFormat('yyyy-MM-dd – kk:mm').format(now);
    

    This code snippet formats the current date and time to a more readable form, removing the unwanted milliseconds.

Alternative Methods

While the intl package is widely used, there are other methods available that do not require any external dependencies. For example, you can manually convert the DateTime to a string and manipulate it:

DateTime now = DateTime.now();
String convertedDateTime = "${now.year.toString()}-${now.month.toString().padLeft(2,'0')}-${now.day.toString().padLeft(2,'0')} ${now.hour.toString().padLeft(2,'0')}-${now.minute.toString().padLeft(2,'0')}";

Conclusion

Formatting DateTime in Flutter can be efficiently handled using the intl package, which offers a simple and flexible approach. However, for those who prefer not to use external dependencies, manual string manipulation is a viable alternative.

Enhance Your App Testing with Repeato

As you continue to develop and test your Flutter applications, consider using Repeato, a no-code test automation tool. Repeato allows you to create, run, and maintain automated tests for iOS and Android apps swiftly and efficiently. Its computer vision and AI capabilities can streamline your test automation process, making it easier to ensure your DateTime formatting and other functionalities are working as intended.

Like this article? there’s more where that came from!