How to convert DateTime to String In dart?

3,291

Solution 1

You can use intl package. Consider a code snippet like a below:

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

Solution 2

There is a pretty straightforward way to read dates and write them in any format. Here is just one sample:

DateFormat.yMMMEd().format(DateTime.parse("2021-01-23 19:26:00"))

Here is the article about working with dates.

Here is the sample to localize the date with Intl package:

Intl.defaultLocale = 'es';
DateFormat.jm().format(DateTime.now());
Share:
3,291
Shahriyar Hasanov
Author by

Shahriyar Hasanov

Updated on December 30, 2022

Comments

  • Shahriyar Hasanov
    Shahriyar Hasanov over 1 year

    when it comes to api, "createdAt": "2021-01-23 19:26:00", how do I convert it as "January 23", for example?

  • Shahriyar Hasanov
    Shahriyar Hasanov almost 3 years
    it works, but how can I translate it into my own language? are there docs about it?
  • Shahriyar Hasanov
    Shahriyar Hasanov almost 3 years
    it works, but how can I translate it into my own language? are there docs about it?
  • Uladzislau Kaminski
    Uladzislau Kaminski almost 3 years
    Take a look on the article, it shows the way to choose format. Or what do you mean but you own language?
  • Steve
    Steve almost 3 years
    Do you mean to internationalise ?
  • Shahriyar Hasanov
    Shahriyar Hasanov almost 3 years
    it mean look localizations i can't
  • Shahriyar Hasanov
    Shahriyar Hasanov almost 3 years
    I just want to translate the names of the months in English into my own language?
  • Uladzislau Kaminski
    Uladzislau Kaminski almost 3 years
    you can do it with Intl package. I've added it to my answer
  • Steve
    Steve almost 3 years
    And what is your language? Both solutions I've provided support locale customisation
  • Shahriyar Hasanov
    Shahriyar Hasanov almost 3 years
    my language is Azerbaijani.