2 ways to format DateTime in Flutter

Last updated on October 13, 2020 The Frog Loading... Post a comment

In Flutter, you can format DateTime by writing your own function or using a third-party package.

Using your own function

void main() {
  String myFormat(DateTime time) {
    // return the "yyyy-MM-dd HH:mm:ss" format
    String year = time.year.toString();

    String month = time.month.toString();
    // convert 0, 1, 2, 3, ..., 9 to 00, 01, 02, 03, ..., 09
    if(month.length < 2){
      month = "0" + month;
    }

    String day = time.day.toString();
    // convert 0, 1, 2, 3, ..., 9 to 00, 01, 02, 03, ..., 09
    if(day.length < 2){
      day = "0" + day;
    }

    String hour = time.hour.toString();
    // convert 0, 1, 2, 3, ..., 9 to 00, 01, 02, 03, ..., 09
    if(hour.length < 2){
      hour = "0" + hour;
    }

    String minute = time.minute.toString();
    // convert 0, 1, 2, 3, ..., 9 to 00, 01, 02, 03, ..., 09
    if(minute.length < 2){
      minute = "0" + minute;
    }

    String second = time.second.toString();
    // convert 0, 1, 2, 3, ..., 9 to 00, 01, 02, 03, ..., 09
    if(second.length < 2){
      second = "0" + second;
    }

    return "$year-$month-$day $hour:$minute:$second";
  }
  
  // Testing
  DateTime currentTime = DateTime.now();
  final time = myFormat(currentTime);
  print(time);
}

The output should be in this form:

2020-10-13 09:31:08

Using third-party packages

One of the best packages for formatting DateTime is intl.

1. Installation

Add intl: ^0.16.1 to the dependencies section of your pubspec.yaml file like this:

dependencies:
  intl: ^0.16.1

Run:

flutter pub get

2. Usage

import 'package:intl/intl.dart';
void main() {
  DateTime currentTime = DateTime.now();

  // the "dd/MM/yyyy HH:mm" format
  print(DateFormat.yMd().add_jm().format(currentTime));

  // just the date
  print(DateFormat.yMd().format(currentTime));
}

Output:

10/13/2020 9:53 PM
10/13/2020

Related Articles

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x