262

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?

Quick learner
  • 10,632
  • 4
  • 45
  • 55
Nitneuq
  • 3,866
  • 13
  • 41
  • 64

16 Answers16

498

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);
TheMisir
  • 4,083
  • 1
  • 27
  • 37
boformer
  • 28,207
  • 10
  • 81
  • 66
  • 76
    Don't forget to add `intl: 0.15.7` dependency to your `pubspec.yaml` file. Latest version of the library can be found [here](https://pub.dartlang.org/packages/intl). – Defuera Nov 03 '18 at 20:12
  • 1
    Anyone else getting that static members cannot be accessed in initializers? – MrPool Jan 02 '20 at 12:07
  • 1
    @MrPool Yes, same issue with the static members cannot be accessed in initializers. Very frustrating because having the date static makes no sense. – Michael T Apr 28 '20 at 10:33
  • 3
    If you want to use a specific locale, you can use eg.: `DateFormat.yMd(myLocale.languageCode).format(now)` where you obtain the current device locale like this: `Locale myLocale = Localizations.localeOf(context)` – Zsolt May 24 '20 at 13:23
95

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");
CopsOnRoad
  • 237,138
  • 77
  • 654
  • 440
84

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

Quick learner
  • 10,632
  • 4
  • 45
  • 55
  • 7
    Besides the missing dash, this is the best way to go without adding yet another dependency. – 01000101 May 19 '20 at 18:03
  • 1
    This is good but the hour is returning non-US standard time on a 24 hour clock. Arithmetic.... sigh... forget it, i'll just get the package – Amir Memon May 28 '20 at 13:58
  • What's the problem with external dependencies? That's how things works in 2020 :-) – funder7 Jan 01 '21 at 22:11
  • 2
    @funder7 - Every external dependency you add is a potential point of failure in your code base. Dependencies are maintained by 3rd parties - so you have absolutely no guarantee over the functionality & stability of this 3rd party code at each iteration (i.e. version change). It is thus wise to have as few dependencies in your production code as possible. – SilSur Jan 27 '21 at 20:22
  • 1
    Yeah, that can be true, but you can stick to a fixed version if you fear regressions. Users who develop external libraries usually provides good code: consider the above snippet: it's returning the date in the expected format, but in my opinion that's ugly, considering that Flutter has intl library which handles date/time internationalization very well. It's tested code, probably way more better than what you get with cut'n'paste. Obviously I wouldn't import an external library for string concatenation..but I think you got my point. Cheers ;) – funder7 Jan 28 '21 at 16:30
  • 2
    This was ideal without adding a package. Only thing is I think you need to add `padLeft(2,'0')` to the minute's field also otherwise 14:07 will show up as 14:7 – its_broke_again Aug 04 '21 at 06:03
30

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
zizutg
  • 1,070
  • 14
  • 20
  • This works well whithout any package. Below is the way of doing it. DateTime now = DateTime.now(); DateTime date = new DateTime(now.year, now.month, now.day); print(date.toString().substring(0, 10) ); – Raju Gupta Dec 18 '20 at 08:56
26

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
Jama Mohamed
  • 3,057
  • 4
  • 29
  • 43
14

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
SilenceCodder
  • 2,874
  • 24
  • 28
10

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)
asli
  • 433
  • 1
  • 5
  • 10
9

You could use DateTime.now() or clock.now(). Sample with clock lib:

import 'package:clock/clock.dart';

DateTime now = clock.now();
String formattedDate = DateFormat('yyyy-MM-dd – kk:mm').format(now);
Bruno Minuk
  • 143
  • 1
  • 2
  • 4
7

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}';
Jean Patricio
  • 331
  • 3
  • 8
6

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())}'
  • Note if you want to see 12:00 o'clock (24 h format) in 12 h format as 12:00 not the 00:00 use "hh" and "HH" instead of "kk" and "KK" ` h hour in am/pm (1~12) (Number) H hour in day (0~23) (Number) k hour in day (1~24) (Number) K hour in am/pm (0~11) (Number)` – Nazarii Boichyshyn Sep 06 '21 at 15:44
5

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]}";
Mohd Danish Khan
  • 1,044
  • 11
  • 12
5
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");
Rahul Baghaniya
  • 291
  • 4
  • 5
4

easiest direct way without installing extra package is

to get date:

datetime.toIso8601String().split("T")[0];

to get time:

datetime.toIso8601String().split("T")[1];
evals
  • 1,750
  • 2
  • 18
  • 28
1

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.

Jeppe
  • 1,830
  • 3
  • 24
  • 33
1

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/

  • Please provide additional details in your answer. As it's currently written, it's hard to understand your solution. – Community Sep 10 '21 at 13:58
-3

Usa esta opción que puedes personalizar:

static String formatDateTime(DateTime fecha, String formato) {
    var _index = 0;
    var _letra = '';
    var _fecha = '';
    var _auxiliar = '';
    //
    //Evalua todas las letras
    while (_letra != '[/]') {
      _letra = _index < formato.length ? formato[_index++] : '[/]';
      //
      //suma las letra para luego aplicarles el formato
      if (_auxiliar.isEmpty || _auxiliar[0] == _letra) {
        _auxiliar += _letra;

        continue;
      }
      //
      //aplica el formato de las letras acumuladas
      switch (_auxiliar) {
        case 'yy':
          _fecha += fecha.year.toString().substring(2);
          break;
        case 'yyyy':
          _fecha += fecha.year.toString();
          break;
        case 'M':
          _fecha += fecha.month.toString();
          break;
        case 'MM':
          _fecha +=
              fecha.month < 10 ? '0${fecha.month}' : fecha.month.toString();
          break;
        case 'd':
          _fecha += fecha.day.toString();
          break;
        case 'dd':
          _fecha += fecha.day < 10 ? '0${fecha.day}' : fecha.day.toString();
          break;
        case 'h':
          _fecha += 12 < fecha.hour
              ? (fecha.hour - 12).toString()
              : fecha.hour.toString();
          break;
        case 'hh':
          _fecha += fecha.hour < 10
              ? '0${fecha.hour}'
              : 12 < fecha.hour
                  ? (fecha.hour - 12).toString()
                  : fecha.hour.toString();
          break;
        case 'H':
          _fecha += fecha.hour.toString();
          break;
        case 'HH':
          _fecha += fecha.hour < 10 ? '0${fecha.hour}' : fecha.hour.toString();
          break;
        case 'm':
          _fecha += fecha.minute.toString();
          break;
        case 'mm':
          _fecha +=
              fecha.minute < 10 ? '0${fecha.minute}' : fecha.minute.toString();
          break;
        case 's':
          _fecha += fecha.second.toString();
          break;
        case 'ss':
          _fecha +=
              fecha.second < 10 ? '0${fecha.second}' : fecha.second.toString();
          break;
        case 't':
          _fecha += fecha.hour < 12 ? 'a' : 'p';
          break;
        case 'tt':
          _fecha += fecha.hour < 12 ? 'am' : 'pm';
          break;
        case 'f':
        case 'ff':
        case 'fff':
        case 'ffff':
          _fecha += fecha.millisecond.toString().substring(0, _auxiliar.length);
          break;
        case 'z':
          if (fecha.isUtc) {
            _fecha += '0';
          } else {
            _fecha +=
                (fecha.timeZoneOffset.inMinutes / 60).truncate().toString();
          }
          break;
        case 'zz':
          if (fecha.isUtc) {
            _fecha += '00';
          } else {
            var _horas = (fecha.timeZoneOffset.inMinutes / 60).truncate();

            _fecha += (fecha.timeZoneOffset.inMinutes < 0 ? '-' : '+') +
                (_horas < 10 ? '0$_horas' : _horas.toString());
          }
          break;
        case 'zzz':
          if (fecha.isUtc) {
            _fecha += '00:00';
          } else {
            _fecha += (fecha.timeZoneOffset.inMinutes < 0 ? '-' : '+') +
                formatDateTime(
                    DateTime.fromMillisecondsSinceEpoch(
                        fecha.timeZoneOffset.inMilliseconds),
                    'hh:mm');
          }
          break;
        default:
          _fecha += _auxiliar;
          break;
      }
      //
      //siguiente
      _auxiliar = _letra;
    }
    //
    //Fin
    return _fecha;
  }

Usalo de la siguiente manera:

print(formatDateTime(DateTime.now().toUtc(), 'dd-MM-yyyy hh:mm tt'));
print(formatDateTime(DateTime.now().toUtc(), 'dd-MM-yyyy hh:mm tt (GTM zzz)'));
// 28-07-2022 04:52:59 pm
// 28-07-2022 04:52:59 pm (GTM -6:00)

El que no le guste el español lo puede traducir con google como hago yo con el inglés, saludos.

Moises Conejo
  • 157
  • 1
  • 5