How to format DateTime in Flutter

AndroidIosFlutterDatetimeDart

Android Problem Overview


I am trying to display the current DateTime in a Text widget after tapping on a button. The following works, but I'd like to change the format.

Current approach

DateTime now = DateTime.now();
currentTime = new DateTime(now.year, now.month, now.day, now.hour, now.minute);
 Text('$currentTime'), 

Result

YYYY-MM-JJ HH-MM:00.000

Question

How can I remove the :00.000 part?

Android Solutions


Solution 1 - Android

You can use DateFormat from intl package.

import 'package:intl/intl.dart';
    
DateTime now = DateTime.now();
String formattedDate = DateFormat('yyyy-MM-dd – kk:mm').format(now);

Solution 2 - Android

Add intl package to your pubspec.yaml file.

import 'package:intl/intl.dart';

DateFormat dateFormat = DateFormat("yyyy-MM-dd HH:mm:ss");

Converting DateTime object to String

String string = dateFormat.format(DateTime.now());

Converting String to DateTime object

DateTime dateTime = dateFormat.parse("2019-07-19 8:40:23");

Solution 3 - Android

With this approach, there is no need to import any library.

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')}";

Output

> 2020-12-05 14:57

Solution 4 - Android

Try out this package, Jiffy, it also runs on top of Intl, but makes it easier using momentjs syntax. See below

import 'package:jiffy/jiffy.dart';   

var now = Jiffy().format("yyyy-MM-dd HH:mm:ss");

You can also do the following

var a = Jiffy().yMMMMd; // October 18, 2019

And you can also pass in your DateTime object, A string and an array

var a = Jiffy(DateTime(2019, 10, 18)).yMMMMd; // October 18, 2019

var a = Jiffy("2019-10-18").yMMMMd; // October 18, 2019

var a = Jiffy([2019, 10, 18]).yMMMMd; // October 18, 2019

Solution 5 - Android

Here's my simple solution. That does not require any dependency.

However, the date will be in string format. If you want the time then change the substring values

print(new DateTime.now()
            .toString()
            .substring(0,10)
     );   // 2020-06-10

Solution 6 - Android

there is some change since the 0.16 so here how i did,

import in the pubspec.yaml

dependencies:
      flutter:
        sdk: flutter
      intl: ^0.16.1

then use

  txdate= DateTime.now()


  DateFormat.yMMMd().format(txdate)

Solution 7 - Android

Use this function

todayDate() {
    var now = new DateTime.now();
    var formatter = new DateFormat('dd-MM-yyyy');
    String formattedTime = DateFormat('kk:mm:a').format(now);
    String formattedDate = formatter.format(now);
    print(formattedTime);
    print(formattedDate);
  }

Output:

08:41:AM
21-12-2019

Solution 8 - Android

You can also use this syntax. For YYYY-MM-JJ HH-MM:

var now = DateTime.now();
var month = now.month.toString().padLeft(2, '0');
var day = now.day.toString().padLeft(2, '0');
var text = '${now.year}-$month-$day ${now.hour}:${now.minute}';

Solution 9 - Android

DateTime.now() is deprecated, use clock.now() instead:

import 'package:clock/clock.dart';

DateTime now = clock.now();
String formattedDate = DateFormat('yyyy-MM-dd – kk:mm').format(now);

Solution 10 - Android

What if user is US citizen but wants to see everything in 24hour format - then
showing 12/24 hour based of locale will not satisfy user

 // getting system settings 12/24 h format
      if (MediaQuery.of(context).alwaysUse24HourFormat){
        timeFormat = new DateFormat("kk:mm", languageCode); //24h format
      }
      else{
        timeFormat = new DateFormat("KK:mm a", languageCode); //12h format
      }
//then use it:
 '${timeFormat.format DateTime.now())}'

Solution 11 - Android

Use String split method to remove :00.000

var formatedTime = currentTime.toString().split(':')
Text(formatedTime[0])

======= OR USE BELOW code for YYYY-MM-DD HH:MM:SS format without using library ====

var stringList =  DateTime.now().toIso8601String().split(new RegExp(r"[T\.]"));
var formatedDate = "${stringList[0]} ${stringList[1]}";

Solution 12 - Android

static String convertDateFormat(String dateTimeString, String oldFormat, String 
           newFormat) {
        DateFormat newDateFormat = DateFormat(newFormat);
        DateTime dateTime = DateFormat(oldFormat).parse(dateTimeString);
        String selectedDate = newDateFormat.format(dateTime);
        return selectedDate;
            }

call this method this way

 convertDateFormat(inputDate, "dd-mm-yyyy", "d MMM yyyy");

Solution 13 - Android

You cant format dates in dart ,so you require to use external packages ,I would recommend this article : https://www.geeksforgeeks.org/format-dates-in-flutter/

Solution 14 - Android

How about a simple extension method for DateTime. Run-time is probably not great, since we're iterating the string multiple times and iterating over each % format option. Could probably walk through once and replace % greedily.

extension DateTimeFormat on DateTime {

  /// Supports the following, inspired by: https://linux.die.net/man/3/strptime
  /// %Y: The year, including century (for example, 1991).
  /// %m: The month number (1-12).
  /// %d: The day of month (1-31).
  /// %H: The hour (0-23).
  /// %M: The minute (0-59).
  /// %S: The second (0-59).
  String format(String formatString) {
    var hourString = hour.toString();
    var dayString = day.toString();
    var monthString = month.toString();
    var minuteString = minute.toString();
    var secondString = second.toString();
    var yearString = year.toString();

    var map = {
      '%H': hourString.padLeft(3 - hourString.length, '0'), // the pad values here are the desired length + 1
      '%d': dayString.padLeft(3 - dayString.length, '0'),
      '%m': monthString.padLeft(3 - monthString.length, '0'),
      '%M': minuteString.padLeft(3 - minuteString.length, '0'),
      '%S': secondString.padLeft(3 - secondString.length, '0'),
      '%Y': yearString.padLeft(5 - yearString.length, '0'),
    };
    return map.entries.fold(formatString, (acc, entry) => acc.replaceAll(entry.key, entry.value));
  }
}

Usage:

print(DateTime(2021, 10, 16, 4, 4, 4, 4, 4).format('%Y-%m-%d-%H-%M-%S'));
// '2021-10-16-04-04-04'

Feel free to suggest changes.

Solution 15 - Android

The best and easiest way to convert a sting int Dateformat is,

  print(DateTime.parse('2020-01-02')); // 2020-01-02 00:00:00.000
  print(DateTime.parse('20200102')); // 2020-01-02 00:00:00.000
  print(DateTime.parse('-12345-03-04')); // -12345-03-04 00:00:00.000
  print(DateTime.parse('2020-01-02 07')); // 2020-01-02 07:00:00.000
  print(DateTime.parse('2020-01-02T07')); // 2020-01-02 07:00:00.000
  print(DateTime.parse('2020-01-02T07:12')); // 2020-01-02 07:12:00.000
  print(DateTime.parse('2020-01-02T07:12:50')); // 2020-01-02 07:12:50.000
  print(DateTime.parse('2020-01-02T07:12:50Z')); // 2020-01-02 07:12:50.000Z
  print(DateTime.parse('2020-01-02T07:12:50+07')); // 2020-01-02 00:12:50.000Z
  print(DateTime.parse('2020-01-02T07:12:50+0700')); // 2020-01-02 00:12:50.00
  print(DateTime.parse('2020-01-02T07:12:50+07:00')); // 2020-01-02 00:12:50.00

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNitneuqView Question on Stackoverflow
Solution 1 - AndroidboformerView Answer on Stackoverflow
Solution 2 - AndroidCopsOnRoadView Answer on Stackoverflow
Solution 3 - AndroidQuick learnerView Answer on Stackoverflow
Solution 4 - AndroidJama MohamedView Answer on Stackoverflow
Solution 5 - AndroidzizutgView Answer on Stackoverflow
Solution 6 - AndroidasliView Answer on Stackoverflow
Solution 7 - AndroidSilenceCodderView Answer on Stackoverflow
Solution 8 - AndroidJean CarlosView Answer on Stackoverflow
Solution 9 - AndroidBruno MinukView Answer on Stackoverflow
Solution 10 - AndroidNazarii BoichyshynView Answer on Stackoverflow
Solution 11 - AndroidMohd Danish KhanView Answer on Stackoverflow
Solution 12 - AndroidRahul BaghaniyaView Answer on Stackoverflow
Solution 13 - AndroidMohammad BilalView Answer on Stackoverflow
Solution 14 - AndroidJeppeView Answer on Stackoverflow
Solution 15 - AndroidAnandh KrishnanView Answer on Stackoverflow