361

I have an instance of DateTime and I would like to format that to a String. How do I do that? I want to turn the date into a string, something like "2013-04-20".

24 Answers 24

747

You can use the intl package (installer) to format dates.

For en_US formats, it's quite simple:

import 'package:intl/intl.dart';

main() {
  final DateTime now = DateTime.now();
  final DateFormat formatter = DateFormat('yyyy-MM-dd');
  final String formatted = formatter.format(now);
  print(formatted); // something like 2013-04-20
}

There are many options for formatting. From the docs:

ICU Name                   Skeleton
--------                   --------
DAY                          d
ABBR_WEEKDAY                 E
WEEKDAY                      EEEE
ABBR_STANDALONE_MONTH        LLL
STANDALONE_MONTH             LLLL
NUM_MONTH                    M
NUM_MONTH_DAY                Md
NUM_MONTH_WEEKDAY_DAY        MEd
ABBR_MONTH                   MMM
ABBR_MONTH_DAY               MMMd
ABBR_MONTH_WEEKDAY_DAY       MMMEd
MONTH                        MMMM
MONTH_DAY                    MMMMd
MONTH_WEEKDAY_DAY            MMMMEEEEd
ABBR_QUARTER                 QQQ
QUARTER                      QQQQ
YEAR                         y
YEAR_NUM_MONTH               yM
YEAR_NUM_MONTH_DAY           yMd
YEAR_NUM_MONTH_WEEKDAY_DAY   yMEd
YEAR_ABBR_MONTH              yMMM
YEAR_ABBR_MONTH_DAY          yMMMd
YEAR_ABBR_MONTH_WEEKDAY_DAY  yMMMEd
YEAR_MONTH                   yMMMM
YEAR_MONTH_DAY               yMMMMd
YEAR_MONTH_WEEKDAY_DAY       yMMMMEEEEd
YEAR_ABBR_QUARTER            yQQQ
YEAR_QUARTER                 yQQQQ
HOUR24                       H
HOUR24_MINUTE                Hm
HOUR24_MINUTE_SECOND         Hms
HOUR                         j
HOUR_MINUTE                  jm
HOUR_MINUTE_SECOND           jms
HOUR_MINUTE_GENERIC_TZ       jmv
HOUR_MINUTE_TZ               jmz
HOUR_GENERIC_TZ              jv
HOUR_TZ                      jz
MINUTE                       m
MINUTE_SECOND                ms
SECOND                       s

For non-en_US dates, you need to explicitly load in the locale. See the DateFormat docs for more info. The date_symbol_data_local.dart contains all of the formats for each country/language, if you would like a more in-depth look.

12
  • Is intl broken? Uncaught Error: FileSystemException: Cannot open file, path = 'E:\dart\ws\web\packages\intl\intl.dart' (OS Error: The system cannot find the path specified. Sep 21, 2014 at 17:47
  • 3
    Is there any way to add milliseconds to the format?
    – Kaspi
    Dec 1, 2015 at 12:08
  • 3
    requires in pubspec.yaml dependencies: intl: ^0.15.7
    – murt
    Mar 10, 2019 at 15:12
  • 1
    @Kaspi try 'S' for fractional second
    – madlick71
    Jul 3, 2020 at 11:56
  • 1
    ICU format names are also available here with more examples. Jun 20, 2022 at 8:28
69

This will work too:

DateTime today = new DateTime.now();
String dateSlug ="${today.year.toString()}-${today.month.toString().padLeft(2,'0')}-${today.day.toString().padLeft(2,'0')}";
print(dateSlug);
5
  • 7
    This is not advisable because it is not localized in a users locale.
    – DustinB
    Feb 11, 2021 at 3:05
  • @DustinB Are you sure? It seems to be localized in my case, but if it isn't, then just convert it. DateTime.toLocal() should do the trick.
    – EzPizza
    Jul 28, 2021 at 7:26
  • 1
    Well, it is doing string concatenation in the format of YEAR-MM-DD. That may match your current locale, but definitely not everyones. In US, it is more likely to use MM/DD/YYYY for example.
    – DustinB
    Jul 29, 2021 at 14:26
  • 1
    @EzPizza toLocal() is a timezone conversation not an international conversion. Mar 13, 2022 at 19:21
  • 1
    @RalphShillington Oops, I actually thought the question was about timezones. Yeah this solution only works for a specific locale then.
    – EzPizza
    Mar 14, 2022 at 14:52
50

pubspec.yaml:

dependencies:
  intl:

main.dart:

import 'package:intl/intl.dart'; // for date format
import 'package:intl/date_symbol_data_local.dart'; // for other locales

void main() {
  var now = DateTime.now();
  print(DateFormat().format(now)); // This will return date using the default locale
  print(DateFormat('yyyy-MM-dd hh:mm:ss').format(now));
  print(DateFormat.yMMMMd().format(now)); // print long date 
  print(DateFormat.yMd().format(now)); // print short date 
  print(DateFormat.jms().format(now)); // print time 

  initializeDateFormatting('es'); // This will initialize Spanish locale
  print(DateFormat.yMMMMd('es').format(now)); // print long date in Spanish format
  print(DateFormat.yMd('es').format(now)); // print short date in Spanish format
  print(DateFormat.jms('es').format(now)); // print time in Spanish format
}

Result:

May 31, 2020 5:41:42 PM
2020-05-31 05:41:42
May 31, 2020
5/31/2020
5:41:42 PM
31 de mayo de 2020
31/5/2020
17:41:42
1
  • This is the best solution because be adapt to locale Aug 17, 2022 at 7:51
41

You can also specify the date format like stated earlier: https://pub.dev/documentation/intl/latest/intl/DateFormat-class.html

import 'package:intl/intl.dart';
String formatDate(DateTime date) => new DateFormat("MMMM d").format(date);

Produces: March 4

35

If someone wants to convert a date in string format to some other string format first use DateTime.parse("2019-09-30") then pass it to DateFormat("date pattern").format() like

dateFormate = DateFormat("dd-MM-yyyy").format(DateTime.parse("2019-09-30"));

Reference: Dart - How to change format of simple date string which is in yyyy-MM-dd to dd-MM-yyyy

3
  • 1
    your code uses DateFormat but your text says DateTime.format() Jan 7, 2020 at 21:11
  • Oops! a blunder. Changed :)
    – Shashank
    Jan 8, 2020 at 5:01
  • This question is specifically about converting a DateTime to a String (formatting). If you want to convert a String to a DateTime (parsing), then see stackoverflow.com/q/49385303.
    – jamesdlin
    May 28, 2021 at 18:48
23

You can use this method as well, if you don't want to add another library

  DateTime dateTime = DateTime.now();
  String YYYY_MM_DD = dateTime.toIso8601String().split('T').first;
  print(YYYY_MM_DD); //2020-11-23

21

This give you the date like in a social network : ["today","yesterday","dayoftheweek",etc..]

void main() {
      DateTime now = new DateTime(2018,6,26);
      print(date(now));
    }
    
    String date(DateTime tm) {
      DateTime today = new DateTime.now();
      Duration oneDay = new Duration(days: 1);
      Duration twoDay = new Duration(days: 2);
      Duration oneWeek = new Duration(days: 7);
      String month;
      switch (tm.month) {
        case 1:
          month = "january";
          break;
        case 2:
          month = "february";
          break;
        case 3:
          month = "march";
          break;
        case 4:
          month = "april";
          break;
        case 5:
          month = "may";
          break;
        case 6:
          month = "june";
          break;
        case 7:
          month = "july";
          break;
        case 8:
          month = "august";
          break;
        case 9:
          month = "september";
          break;
        case 10:
          month = "october";
          break;
        case 11:
          month = "november";
          break;
        case 12:
          month = "december";
          break;
      }
    
      Duration difference = today.difference(tm);
    
      if (difference.compareTo(oneDay) < 1) {
        return "today";
      } else if (difference.compareTo(twoDay) < 1) {
        return "yesterday";
      } else if (difference.compareTo(oneWeek) < 1) {
        switch (tm.weekday) {
          case 1:
            return "monday";
          case 2:
            return "tuesday";
          case 3:
            return "wednesday";
          case 4:
            return "thursday";
          case 5:
            return "friday";
          case 6:
            return "saturday";
          case 7:
            return "sunday";
        }
      } else if (tm.year == today.year) {
        return '${tm.day} $month';
      } else {
        return '${tm.day} $month ${tm.year}';
      }
    }
3
  • 3
    Very useful - thank you. Add this additional line at top of method if you are passing dates which have a time, otherwise 'yesterday' may not work: tm = DateTime(tm.year, tm.month, tm.day); Jun 3, 2020 at 19:00
  • Instead of the switch statement, wouldnt it be better to use @RodyDavis answer of using import 'package:intl/intl.dart'; String formatDate(DateTime date) => new DateFormat("MMMM").format(date); that will also set it up for anyone who then wants it to display in Spanish, Arabic etc.. those additional steps can be found in this SO Aug 11, 2022 at 16:46
  • and using DateFormat("EEEE") for the days Aug 11, 2022 at 16:56
19

You can use the intl package to format dates in flutter.

void main() {
  final DateTime now = DateTime.now();
  final DateFormat format = DateFormat('yyyy-MM-dd');
  final String formatted = format.format(now);
  // 2021-03-02
}

or you can use date_format package to format dates in flutter.

import 'package:date_format/date_format.dart';

final formattedStr = formatDate(DateTime.now(), [dd, '-', mm, '-', yyyy]);

//02-03-2021
16

Another way, using intl package.

Create an extension of DateTime:

date_time_extension.dart

import 'package:intl/date_symbol_data_local.dart';
import 'package:intl/intl.dart';

extension DateTimeExtension on DateTime {
  String format([String pattern = 'dd/MM/yyyy', String? locale]) {
    if (locale != null && locale.isNotEmpty) {
      initializeDateFormatting(locale);
    }
    return DateFormat(pattern, locale).format(this);
  }
}

Import this file where you are going to use DateTime type, and you can use it like this:

DateTime.now().format();

DateTime.now().format('MM/yyyy');

DateTime.now().format('MM/yyyy', 'es');
13

There is a package date_format

dependencies:
    date_format:

code

import 'package:date_format/date_format.dart';

final formattedStr = formatDate(
    yourDateTime, [dd, '.', mm, '.', yy, ' ', HH, ':', nn]);

// output example "29.03.19 07:00"

Pay attention: minutes are nn

link to the package

11

main() {
  final String pattern = 'yyyy-MM-dd';
  final String formatted = DateFormat(pattern).format(DateTime.now());
  print(formatted);
}

Changing yyyy-MM-dd string you can change your date format. I made app for play with this pattern string.

You can experiment format string in my app It made with flutter. https://biplobsd.github.io/EpochConverterApp

Here you can see how can I edit the pattern and this effect showing on top

7

Set your project intl pakage

dateTimeFormet (date){
   //MM-dd-yyyy
   //yyyy-MM-dd 
   return DateFormat('dd-MM-yyyy').format(date);// you can set your formet
}

void main (){
  var date = 01-11-2022 00 : 00
  var _datetime = dateTimeFormet(date);
  print(_dateTime);
}
6
/// Get date as a string for display.
String getFormattedDate(String date) {
  /// Convert into local date format.
  var localDate = DateTime.parse(date).toLocal();

  /// inputFormat - format getting from api or other func.
  /// e.g If 2021-05-27 9:34:12.781341 then format must be yyyy-MM-dd HH:mm
  /// If 27/05/2021 9:34:12.781341 then format must be dd/MM/yyyy HH:mm
  var inputFormat = DateFormat('yyyy-MM-dd HH:mm');
  var inputDate = inputFormat.parse(localDate.toString());

  /// outputFormat - convert into format you want to show.
  var outputFormat = DateFormat('dd/MM/yyyy HH:mm');
  var outputDate = outputFormat.format(inputDate);

  return outputDate.toString();
} 
4

In the case you want to combine several date format into one, this is how we can do using intl.

DateFormat('yMMMd').addPattern(DateFormat.HOUR24_MINUTE).format(yourDateTime))
4

NO DEPENDENCY METHOD [FOR DISPLAYING DATE AS FORMATTED STRING]

If you want to show your DateTime value as a day/month/year or any other format you like, string interpolation can be handy :

"${_date.day} / ${_date.month} / ${_date.year}"

sample output :

23 / 4 / 1920

I don't want to use any additional library, so i went this way.

3

handling yearly quarters, from string to DateTime, I didn't find proper solution so made this:

    List<String> dateAsList = 'Q1 2001'.split(' ');
    DateTime dateTime = DateTime.now();
    String quarter = dateAsList[0];
    int year = int.parse(dateAsList[1]);
    switch(quarter) {
      case "Q1": dateTime = DateTime(year, 1);
      break;
      case "Q2": dateTime = DateTime(year, 4);
      break;
      case "Q3": dateTime = DateTime(year, 7);
      break;
      case "Q4": dateTime = DateTime(year, 10);
      break;
    }
2

To get a nice user-friendly string that includes both the date and the time, you can use this:

import 'package:intl/intl.dart';

main() {
  final DateTime someDateTime = DateTime(2017, 9, 7, 17, 30);
  final DateFormat formatter = DateFormat.yMMMd().add_jms();
  final String formatted = formatter.format(someDateTime);
  print(formatted); // Sep 7, 2017 5:30:00 PM (in the US)
}
0
import 'package:intl/intl.dart';

main() {
  var formattedDate = new DateTime.Format('yyyy-MM-dd').DateTime.now();
  print(formattedDate); // something like 2020-04-16
}

For more details can refer DateFormat Documentation

0
String formatDate(String date) {
    return date.substring(0, 10).split('-').reversed.join().replaceAll('-', '/');
    
  }

From format "yyyy-mm-dd H:i:s"

0
0
 String dateConverter(String date) {
    // Input date Format
    final format = DateFormat("dd-MM-yyyy");
    DateTime gettingDate = format.parse(date);
    final DateFormat formatter = DateFormat('yyyy-MM-dd');
    // Output Date Format
    final String formatted = formatter.format(gettingDate);
    return date;
  }
0

A simpler way:

new DateFormat("dd-MM-y").format(YOUR_DATETIME_HERE)
1
  • 1
    Previous answers seem to cover this already.
    – Timothy G.
    Jun 2, 2021 at 1:42
0

Use "H:mm" to see full minutes like 13:08 not 13:8

1
0

Since the flutter usual Datetime library doesn't know the locale for Germany - neither de, nor DE, nor de_DE, nor de-DE or any other combinations, for example if you want to have the name of the month or the name of the day written in human readable string, I suggest you to use the following code.

install pub flutter pub add date_format

String formattedDate = formatDate(DateTime(year, month, day),[dd,'. ', MM, ' ', yyyy], locale: GermanDateLocale());
-2

Current Day:

DateTime.now().day, //something like 26

Current Month:

DateTime.now().month, //something like 4

Current Year:

DateTime.now().year, //something like 2022

Current Houre:

DateTime.now().hour, //something like 12

Current Minute:

DateTime.now().minute, //something like 13

Current Second:

DateTime.now().second, //something like 44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.