tomaszkubacki
tomaszkubacki

Reputation: 3262

Is there any way to localize numbers and dates in 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

Upvotes: 5

Views: 1941

Answers (3)

Kai Sellgren
Kai Sellgren

Reputation: 30292

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

Upvotes: 3

Alan Knight
Alan Knight

Reputation: 2971

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.

Upvotes: 2

joan
joan

Reputation: 2541

http://api.dartlang.org/docs/releases/latest/intl/Intl.html

From the page: The Intl class provides a common entry point for internationalization related tasks.

Upvotes: 0

Related Questions