Reputation: 273
I want to convert date String* to DateTime object.
My String (from API) - ”10 Mart 2021 16:38”
My Locale - Turkey [‘tr’]
How can I convert?
Thanks you!
Upvotes: 3
Views: 2849
Reputation: 3405
Try out Jiffy package, it also supports Turkish local since it runs on top of Inlt, making it easier to work with date and time
Set your locale to a Turkish locale
await Jiffy.setLocale("tr");
Then parse your string date time to Jiffy
DateTime dateTime = Jiffy.parse("10 Mart 2021 16:38", pattern: "dd MMMM yyyy hh:mm").dateTime; // 2021-03-10 16:38:00.000
or simply
Jiffy.setLocale("tr").then((value) {
DateTime dateTime = Jiffy.parse("10 Mart 2021 16:38", "dd MMMM yyyy hh:mm").dateTime;
});
Upvotes: 1
Reputation: 1790
Spending a log of time trying to fix this issue, I've found one working solution:
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);
});
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
Upvotes: 1
Reputation: 3031
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);
});
Upvotes: 2