'Flutter Locale Date String to DateTime

I want to convert date String* to DateTime object.

  • String contains month name in Turkish language like below

My String (from API) - ”10 Mart 2021 16:38”

My Locale - Turkey [‘tr’]

How can I convert?

Thanks you!



Solution 1:[1]

Try the following. Only the en_US locale does not require any initialization. Other locales have to be initialized. For more info visit https://pub.dev/documentation/intl/latest/intl/DateFormat-class.html

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

// Then somewhere in your code:
initializeDateFormatting('tr_TR', null).then((_) {
      final dateAsString = '10 Mart 2021 16:38';
      final format = new DateFormat('dd MMMM yyyy HH:mm', 'tr_TR');
      final date = format.parse(dateAsString);
});

Solution 2:[2]

Try out Jiffy package, it also supports Turkish local since it runs on top of Inlt, makes it easier to work with date and time

Set your locale to Turkish locale

await Jiffy("tr");

Then parse your string date time to Jiffy

DateTime dateTime = Jiffy("10 Mart 2021 16:38", "dd MMMM yyyy hh:mm").dateTime; // 2021-03-10 16:38:00.000

or simply

Jiffy.locale("tr").then((value) {
    DateTime dateTime = Jiffy("10 Mart 2021 16:38", "dd MMMM yyyy hh:mm").dateTime;
});

Solution 3:[3]

Spending a log of time trying to fix this issue, I've found one working solution:

  1. Need to parse the date string ONLY with English locale:

     final dateTime = Intl.withLocale('en_US', () {
         const stringExample = 'Wed, 23 Mar 2022 13:48:05';
         const format = 'EEE, dd MMM yyyy hh:mm:ss';
         return DateFormat(format).parse(stringExample);
     });
    
  2. Localise your date:

     initializeDateFormatting('tr', null).then((_) {
         final localisedDate = DateFormat('dd MMM yyyy').format(dateTime);
     });
    

You can format your date in step 2 directly without initializeDateFormatting method, if desired locale is set for MaterialApp

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 hnnngwdlch
Solution 2 Jama Mohamed
Solution 3