Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to localize numbers and dates in dart?

Tags:

dart

In C# we have CultureInfo which affects the way ToString() works for dates and numbers eg. you can set CurrentCulture by doing:

Thread.CurrentThread.CurrentCulture = new CultureInfo("pl-PL");;

Is there any equivalent for the above in dart?

EDIT:

  1. Short answer is: use intl package (thanks to all for answers)
  2. As Alan Knight pointed below setting locale "by thread" does not make sense in Dart since we do not control threads explicite.
  3. At the moment i write this NumberFormating is work in progress as far as i understand it
like image 601
tomaszkubacki Avatar asked Mar 30 '13 10:03

tomaszkubacki


2 Answers

The intl library will offer you this, although it doesn't affect the behavior of toString().

Here's an example:

Add as a dependency to your pubspec.yaml:

dependencies:
  intl: any # You might specify some version instead of _any_

Then a code sample:

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

main() {
  initializeDateFormatting("en_US", null).then((_) {
    var formatter = new DateFormat.yMd().add_Hm();
    print(formatter.format(new DateTime.now()));
  });
}

The output looks like this:

07/10/1996 12:08 PM

like image 58
Kai Sellgren Avatar answered Oct 23 '22 13:10

Kai Sellgren


Yes, as per the previous entry the Intl library is what you want. You can set the default locale, or use the withLocale method to set it within a function. Setting it by thread doesn't work, as there are no threads. The other major difference is that, since this is all downloaded into the browser, you don't automatically have all the locale data available, but have to go through an async initialization step to load the data. That will probably be switched over to use the new lazy loading features soon.

Also, the locale doesn't affect the system toString() operation but rather you have to use a DateFormat object to print the date. And as it's still work in progress, NumberFormat doesn't work properly for locales yet, but should soon.

like image 32
Alan Knight Avatar answered Oct 23 '22 13:10

Alan Knight